Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...