2011-05-02 34 views
4

我在我的persistence.xml以下属性:如何覆盖persistence.xml中的属性OpenJPA中

<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"/> 

我试图用一个系统属性来覆盖它,因为每docs,所以我已设置:

-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中覆盖属性的正确方法是什么?

回答

4

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

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

1

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

+0

基本上是这样,你必须在所有的明确性SYS通过,看来他们是不默认读取。 – Joel 2011-05-02 14:38:26

1

恐怕你的运气了。所述manual

在JPA中,在运行时所使用的持久性类的标准META-INF/persistence.xml中引导文件中的值覆盖值在上述资源[openjpa.xml],以及与任何系统属性设置一样。

我不知道为什么它是这样的,但它是这样的。

然而,这也是事实:

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

所以,如果你可以在那里得到你的设置,你很好。

+0

没有。你是一个非常有礼貌的家伙! – 2011-05-02 16:15:00

+2

这可能是太阳在我的头上。 – Joel 2011-05-03 11:14:00

0

在较新的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