使用Spring和Hibernate时,persistence.xml是否已经被请求? [英] Is persistence.xml requied when working with Spring and Hibernate?

查看:97
本文介绍了使用Spring和Hibernate时,persistence.xml是否已经被请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring JPA和Hibernate的项目。大部分 persistence.xml 中的内容都可以在Spring applicationContext.xml文件中指定。



更新: Spring 3.1将支持 persistence.xml - 免费的JPA配置,请参阅 Spring 3.1 M2:配置增强功能






darioo的答案适合实际使用,但在技术上不正确。

PersistenceProvider 有两个工厂方法:
$ b $ ul
EntityManagerFactory createEntityManagerFactory(String emName,Map map) - 对于独立环境,将由持久性提供者进行解析。对于应用程序服务器环境,<$ c $> EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info,Map map) c> persistence.xml 由应用程序服务器解析,其内容作为 PersistenceUnitInfo 传递。


Spring的 LocalContainerEntityManagerFactoryBean 模拟应用程序服务器环境。因此,它解析 persistence.xml 本身,将其内容与应用程序上下文中的值合并,并使用第二种工厂方法将其传递给持久性提供程序。



然而,获取 persistence.xml 数据的过程是可配置的:


  • 您可以使用 persistenceXmlLocation 属性来配置 persistence.xml 文件的名称 - 它是有助于避免与应用程序服务器的默认JPA初始化策略发生冲突。

  • 您可以完全覆盖 PersistenceUnitInfo 通过设置自定义 PersistenceUnitManager 策略。


因此,实际上你可以通过编写一个自定义的 PersistenceUnitManager 来配置Spring中的JPA,而不需要 persistence.xml ,尽管这样的管理器是没有开箱即用。


I am using a project with Spring JPA and Hibernate. Most of the things in persistence.xml can be specified in Spring applicationContext.xml file.

So is the persistence.xml required anymore?

Thanks.

解决方案

Update: Spring 3.1 will support persistence.xml-free JPA configuration, see Spring 3.1 M2: Configuration Enhancements.


darioo's answer is good for practical use, but not technically correct.

PersistenceProvider has two factory methods:

  • EntityManagerFactory createEntityManagerFactory(String emName, Map map) - for standalone environments, persistence.xml is to be parsed by persistence provider.

  • EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) - for application server environments, persistence.xml was parsed by application server and its contents is passed as PersistenceUnitInfo.

Spring's LocalContainerEntityManagerFactoryBean emulates the application server environment. Therefore it parses persistence.xml itself, merges its contents with the values from application context, and passes it to the persistence provider using the second factory method.

However, process of obtaining persistence.xml data is configurable:

  • You can configure the name of persistence.xml file using persistenceXmlLocation property - it's useful to avoid conflicts with the default JPA initialization strategies of application servers.

  • You can completely override the source of PersistenceUnitInfo by setting a custom PersistenceUnitManager strategy.

So, actually you can configure JPA in Spring without persistence.xml by writing a custom PersistenceUnitManager, though such a manager is not available out of the box.

这篇关于使用Spring和Hibernate时,persistence.xml是否已经被请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆