我在 persistence.xml 中配置了一个持久性单元,但我有两个数据库。这些数据库在模式方面是相同的。我想做的是:
Persistence.createEntityManagerFactory("unit", primaryProperties);
Persistence.createEntityManagerFactory("unit", secondaryProperties);
属性包含不同的连接设置(用户、密码、jdbc url,...)。
我实际上试过了,似乎 hibernate (我的 jpa 提供者)在第二次调用中返回了相同的实例,没有处理属性。
我需要将配置复制到第二个单元吗?
我把它确定为与我之前想象的不同的东西。上述调用返回的 EntityManagers(和工厂)按预期工作,但 getDelegate()
似乎是问题所在。我需要获取底层 session 以支持我的应用程序中直接依赖于 hibernate api 的遗留代码。我所做的是:
final Session session = (Session) manager.getDelegate();
但不知何故,即使使用在第二个数据库上运行的实体管理器,我也会收到一个在主数据库上运行的 session 。
最佳答案
这很奇怪。根据 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
}
实际上,它只是有效(第二个实例正在使用覆盖的属性)。
关于java - 是否可以从 persistence.xml 共享配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3612328/