LocalContainerEntityManagerFactoryBean实例化未找到persistenceunit

时间:2014-11-07 10:12:46

标签: java spring hibernate spring-boot

我有以下LocalContainerEntityManagerFactoryBean

@Bean
public static LocalContainerEntityManagerFactoryBean fakeEntityManagerFactory(){
    LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
    MergingPersistenceUnitManager persistenceManager = new MergingPersistenceUnitManager();
    persistenceManager.setPersistenceXmlLocation("classpath*:META-INF/fake/persistence.xml");
    bean.setPersistenceUnitManager(persistenceManager);
    bean.setPersistenceUnitName("fake");
    HibernateJpaVendorAdapter jpaVendorAdapter= new HibernateJpaVendorAdapter();
    jpaVendorAdapter.setGenerateDdl(false);
    bean.setJpaVendorAdapter(jpaVendorAdapter);
    return bean;
}

Persistence.xml包含以下内容:

<persistence-unit name="fake" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>fake</jta-data-source>
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
</persistence-unit>

然而,当它设置persistenceUnitName(bean.setPersistenceUnitName(&#34; fake&#34;);)

我得到了例外

  java.lang.IllegalArgumentException: No persistence unit with name 'fake' found

我相信这是因为bean在设置时还没有加载持久性单元。

如何解决这个问题?

修改

我读到.setPersistenceUnitName如果设置persistenceUnitManager则不应该使用:(取自官方文档)

NOTE: Only applied if no external PersistenceUnitManager specified.

但是,如果我将其删除,则会产生:java.lang.IllegalStateException: No persistence units parsed from {classpath*:META-INF/fake/persistence.xml}

1 个答案:

答案 0 :(得分:0)

我对MergingPersistenceUnitManager有类似的问题。 我的解决方案适用于Spring Boot 2.0.3

    persistenceManager.preparePersistenceUnitInfos();
    persistenceManager.setDefaultDataSource(dataSource);

如果未设置dataSource,则无法开始交易。 您无需在代码中设置persistentUnitName。