Is persistence.xml requied when working with Spring and Hibernate?

前端 未结 3 2031
清酒与你
清酒与你 2020-12-04 18:21

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.

S

3条回答
  •  Happy的楠姐
    2020-12-04 19:06

    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.

提交回复
热议问题