2011-05-02 76 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