一个Persistence.xml中的两个持久性单元

时间:2011-03-18 18:14:40

标签: java jpa persistence persistence.xml

我们创建了一些我们所有项目都会使用的库,这些库将提供我们所有系统的基本功能(登录,管理等)。但是应用程序本身可以使用另一个数据库。

我们所做的是使用两个持久单元创建Persistence.xml。并将所有核心库实体打包在一个名为“LN-model.jar”的jar中,以及在“App-model.jar”中输出测试应用程序的所有实体。但出于某种原因,我们仍然会收到以下信息。

  

无法在名为[gfdeploy#/ Users / zkropotkine / WORK / SeguridadCore / dist / gfdeploy /的模块范围内解析与persistence-context-ref-name [xxxxlistener.InicializadorListener / em]对应的持久性单元SeguridadCore-war_war。请验证您的申请。

这是我们的Persistence.xml

<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

<persistence-unit name="x" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/x</jta-data-source>
    <jar-file>App-model.jar</jar-file>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
    </properties> 
</persistence-unit>

<persistence-unit name="y" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/y</jta-data-source>
    <jar-file>LN-model.jar</jar-file>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties/>
</persistence-unit> 

顺便说一下,我们将Persistence.xml放在jar中,然后添加到我们的企业项目(EAR)中。

2 个答案:

答案 0 :(得分:13)

问题是JPA不知道使用哪个持久性单元。当您只有一个持久性单元时,不会发生此问题。要解决此问题,请执行以下操作:

你需要在Ejb中指定一个持久性单元:@PersistenceContext(unitName =“...”)

答案 1 :(得分:8)

您可以添加注释:

@PersistenceUnit(name = "x")
EntityManagerFactory entityManagerFactory;

@PersistenceContext(unitName = "y")
EntityManager entityManager;

或者您可以手动创建它:

EntityManagerFactory emfA = Persistence.createEntityManagerFactory("x", properties);
EntityManagerFactory emfB = Persistence.createEntityManagerFactory("y", properties);

有关详细信息,请参阅以下链接:https://docs.oracle.com/html/E25034_01/usingmultipledbs.htm 非常有用,对我帮助过我!