繁体   English   中英

如何覆盖 OpenJPA 中的 persistence.xml 属性

[英]How to override persistence.xml properties in OpenJPA

我的 persistence.xml 中有以下属性:

<property name="openjpa.ConnectionProperties"
value="DriverClassName=com.mysql.jdbc.Driver,jdbcUrl=jdbc:mysql://localhost:3306/c,user=foo,password=foo,autocommit=false,automaticTestTable=testtable,idleConnectionTestPeriod=60"/>

根据文档我正在尝试使用系统属性覆盖它,所以我设置了:

-Dopenjpa.ConnectionProperties=DriverClassName=com.mysql.jdbc.Driver,jdbcUrl=jdbc:mysql://localhost:3306/bar,user=bar,password=bar,autocommit=false,automaticTestTable=testtable,idleConnectionTestPeriod=60

但它不起作用:OpenJPA 总是从 persistence.xml 读取属性值

只有当persistence.xml 中的属性被删除时,它才会从系统属性中读取值。

这是预期的行为吗?如果是这样,从 persistence.xml 覆盖属性的正确方法是什么?

默认情况下,OpenJPA 在创建 EM/EMF 时不查看 SystemProperties。 在创建 EMF 时尝试传入 System.getProperties()。

Persistence.createEntityManagerFactory("pu_Name", System.getProperties());

你是如何获得 EntityManager 的? 您可以将属性传递给 EntityManagerFactory 并以这种方式覆盖 persistence.xml。

恐怕你运气不好。 手册

在 JPA 中,标准 META-INF/persistence.xml 引导文件中的值由 Persistence class在运行时使用的引导文件,以及上面的任何属性设置覆盖资源

我不知道为什么会这样,但就是这样。

然而,这也是事实:

在运行时传递给 Persistence.createEntityManagerFactory 的 Map 也会覆盖以前的设置,包括在 persistence.xml 中定义的属性。

因此,如果您可以在那里进行设置,那就太好了。

在较新的 OPENJPA ( 7.0.1 ) 中,如果您想要覆盖 persistence.xml 中的属性,您可以传递系统属性或在初始上下文中使用 PU 名称作为前缀,然后将要覆盖的属性作为后缀。

原来的persistence.xml:

<persistence>
   <persistence-unit name="movie-unit">
   <provider>org.hibernate.ejb.HibernatePersistence</provider>
   <jta-data-source>movieDatabase</jta-data-source>
   <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>
   <properties>
     <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
     <property name="hibernate.max_fetch_depth" value="3"/>
   </properties>
   </persistence-unit>
</persistence>

覆盖:

Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");
p.put("movie-unit.hibernate.hbm2ddl.auto", "update");
p.put("movie-unit.hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
context = new InitialContext(p);

http://tomee.apache.org/configuring-persistenceunits-in-tests.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM