JPA实体 - 指定持久性单元?

Sha*_*man 10 database jpa java-ee persistence-unit jpa-2.0

我有一个JavaEE项目,它使用多个持久性单元.有没有办法指定特定JPA实体所属的持久性单元?某些实体位于一个数据源中,而其他实体位于我的第二个数据源中.有没有办法区分使用注释的两个?

Kev*_*vin 9

要指定Entity属于哪个持久性单元,请使用以下persistence.xml文件:

<persistence version="2.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_2_0.xsd">

    <persistence-unit name="user" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>jdbc/myApp</jta-data-source>
        <class>com.company.User</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <!-- properties -->
        </properties>
    </persistence-unit>

    <persistence-unit name="data" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>jdbc/myApp_data</jta-data-source>
        <!--<mapping-file>META-INF/myApp_entities.xml</mapping-file> You can also use mapping files.-->
        <class>com.company.Data</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <!-- properties -->
        </properties>
    </persistence-unit>
</persistence>
Run Code Online (Sandbox Code Playgroud)

注意使用<exclude-unlisted-classes />.

  • 因此,这需要我将每个实体添加到 persistence.xml,而不是使用注释进行发现,对吗? (2认同)
  • 是的。从根本上讲,为了在持久性上下文之间进行选择,您需要列出每个 persistence.xml 中的所有类,或者列出每个实体中的持久性上下文。两者的工作量似乎相同。然而,对于第一个,所有元数据都位于一个位置。 (2认同)