Is persistence.xml requied when working with Spring and Hibernate?
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 asPersistenceUnitInfo
.
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 usingpersistenceXmlLocation
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 customPersistenceUnitManager
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.
persistence.xml
is needed when you're using Hibernate through JPA, even though you're using Spring JPA. If you're using Hibernate directly, then persistence.xml
isn't needed.
The JPA specification does not state anywhere that the file is required, but in the definitions of the contracts of EntityManagerFactory and EntityManager and practically throughout the whole specification, the persistence.xml file is mentioned over and over.
I recently had to deal with the question of whether it is possible to programatically configure JPA 2.0 with Hibernate 3.6 without using persistence.xml at all.
I concluded that this is not possible, although you can configure the file to contain a very minimum configuration. I determined that the file must at least contain the name of your persistence unit. The rest of the info can be programatically provided to the entity manager factory as parameters.
I have never used spring though, therefore I do not know if it uses any tricks to overcome this issue.
精彩评论