2010-08-31 33 views
3

我有一個持久性單元配置在我的persistence.xml中,但我有兩個數據庫。這些數據庫與模式相同。我所試圖做的是:是否可以共享來自persistence.xml的配置?

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

屬性包含不同的連接設置(用戶名,密碼,JDBC URL,...)。
我試過這實際上,似乎hibernate(我的jpa提供程序)在第二次調用中返回相同的實例,而不考慮屬性。

我是否需要將配置複製到第二個單元?


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

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

但不知何故,我收到使用該第二運作一個EntityManager,即使在主數據庫上運行的會話。

+0

好的,我的問題與jpa和/或hibernate無關。我在我的guice綁定中遇到錯誤。 – whiskeysierra 2010-09-01 13:43:46

回答

3

這很奇怪。據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 
} 

其實,這只是工作(和第二個實例使用重寫的屬性)。

+0

我有類似的問題試圖爲EclipseLink做同樣的事情。我能做的最好的就是簡單地使用相同的數據源,但使用不同的持久性單元和我想要的屬性。 – 2010-08-31 21:19:22

+0

@ the-alchemist我不知道該說什麼:)首先,問題是關於Hibernate。其次,不管實現如何,規範都很清楚(第7.2.1節javax.persistence.Persistence類):方法應該使用傳遞的屬性返回EMF。任何其他行爲都是一個錯誤。 – 2010-08-31 21:48:19

相關問題