2010-08-31 57 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

相关问题