Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Entity - Specify Persistence Unit?

I have a JavaEE project that makes use of multiple persistence units. Is there any way to specify which persistence unit a particular JPA Entity belongs to? Some entities are in one data source, while others are in my second data source. Is there a way to differentiate between the two using annotations?

like image 544
Shadowman Avatar asked Apr 25 '13 00:04

Shadowman


People also ask

How is persistence unit defined?

A persistence unit defines a set of all entity classes that are managed by EntityManager instances in an application. This set of entity classes represents the data contained within a single data store.

What is persistent unit in JPA?

A persistence unit defines the details that are required when you acquire an entity manager. To package your EclipseLink JPA application, you must configure the persistence unit during the creation of the persistence. xml file. Define each persistence unit in a persistence-unit element in the persistence.

How do you specify data source in persistence xml?

xml , choose the Source tab. Specify the data source for the persistence unit. Typically, you use the relevant data source alias name to specify the DataSource. Make sure that the value of the jta-data-source tag is the same as the value of the alias tag in the data-source-aliases.

In which file are defined persistence units?

xml file must define a persistence-unit with a unique name in the current scoped classloader. The provider attribute specifies the underlying implementation of the JPA EntityManager.


1 Answers

To specify which persistent unit an Entity belongs to, use the persistence.xml file:

<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>

Note the use of <exclude-unlisted-classes />.

like image 149
Kevin Avatar answered Sep 28 '22 06:09

Kevin