簡體   English   中英

是否可以從persistence.xml共享配置?

[英]Is it possible to share configuration from persistence.xml?

我在persistence.xml中配置了一個持久性單元,但我有兩個數據庫。 關於模式,這些數據庫是相同的。 我想做的是:

Persistence.createEntityManagerFactory("unit", primaryProperties);
Persistence.createEntityManagerFactory("unit", secondaryProperties);

屬性包含不同的連接設置(用戶,密碼,jdbc url,...)。
我實際上嘗試了這一點,似乎hibernate(我的jpa提供程序)在第二次調用中返回相同的實例,而不管理屬性。

我是否需要將配置復制到第二個單元?


我把它釘在了不同於我之前想到的東西上。 上述調用返回的EntityManagers(和Factories)按預期工作,但getDelegate()似乎是問題所在。 我需要獲得底層會話以支持我的應用程序中的遺留代碼,該代碼直接依賴於hibernate api。 我做的是:

final Session session = (Session) manager.getDelegate();

但不知何故,即使使用在第二個數據庫上運行的實體管理器,我也會收到在主數據庫上運行的會話。

這很奇怪。 根據HibernateProvider#createEntityManagerFactory的來源,該方法返回一個新實例:

public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) {
    Ejb3Configuration cfg = new Ejb3Configuration();
    Ejb3Configuration configured = cfg.configure( persistenceUnitName, properties );
    return configured != null ? configured.buildEntityManagerFactory() : null;
}

我絕對不會在這個虛擬測試中得到相同的實例:

@Test
public void testCreateTwoDifferentEMF() {
    Map properties1 = new HashMap();
    EntityManagerFactory emf1 = Persistence.createEntityManagerFactory("MyPu", properties1);
    Map properties2 = new HashMap();
    properties2.put("javax.persistence.jdbc.user", "foo");
    EntityManagerFactory emf2 = Persistence.createEntityManagerFactory("MyPu", properties2);
    assertFalse(emf1 == emf2); //passes
}

實際上,它只是工作(第二個實例使用重寫的屬性)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM