JPA:通过覆盖数据源,在JSE和JUnit中将jp-data-source与persistence.xml一起使用

时间:2018-07-25 08:38:34

标签: java hibernate jpa wildfly

我有这个peristence.xml部署在WildFly上:

  <persistence-unit name="optaweb-employee-rostering-persistence-unit" transaction-type="JTA">
    <jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
    ...
  </persistence-unit>

现在,我想在具有直接JDBC连接的纯Java应用程序中重用它,所以没有JNDI

    Map<String, String> properties = new HashMap<>();
    properties.put("javax.persistence.jdbc.driver", "org.hsqldb.jdbcDriver");
    properties.put("javax.persistence.jdbc.url", "jdbc:hsqldb:mem:testdb");
    properties.put("javax.persistence.jdbc.user", "sa");
    properties.put("javax.persistence.jdbc.password", "");

    // Overwrites transaction-type successfully 
    properties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");

    // TODO overwrite jta-data-source

    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(
            "optaweb-employee-rostering-persistence-unit", properties);

如何覆盖jta-data-source


我尝试了许多JPA属性来覆盖jta-data-source,但没有成功:

    // Overwrites jta-data-source
    // but triggers a JNDI lookup of "" which crashes of course
    properties.put("javax.persistence.jtaDataSource", "");
    // Does not overwrite jta-data-source
    properties.put("javax.persistence.jtaDataSource", null);

    // Does not overwrite jta-data-source
    properties.put("javax.persistence.nonJtaDataSource", "foo");

我还尝试了一些特定于休眠的属性,例如hibernate.transaction.coordinator_classhibernate.connection.datasource,它们的失败结果与上述相同。

1 个答案:

答案 0 :(得分:0)

据我从Hibernate ORM的来源(尤其是org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl#EntityManagerFactoryBuilderImpl(org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor, java.util.Map, java.lang.ClassLoader, org.hibernate.boot.registry.classloading.spi.ClassLoaderService))得知,这些特定的JPA设置会覆盖hibernate.properties或您将提供给Persistence.createEntityManagerFactory的Map中的设置

这可能是一个愚蠢的主意,但是您是否不能做相反的事情,即不是在持久性单元中设置数据源,而是通过WildFly应用程序中的hibernate.properties文件设置呢?然后,您可以在普通的Java应用程序中执行任何操作。