bobbel
bobbel

Reputation: 471

Container-managed EntityManager: multiple managers for single persistence unit?

I have a use-case where I think I need two entity managers, that access the same persistence unit. So essentially I want two persistence contexts on the same database. Is this possible via @PersistenceContext annotations?

I want to write something like the following, but don't know how to tell JPA to inject two different manager instances.

@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;

@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager otherEntityManager;

I think I could switch to application-managed transactions, then I could just create another one using a factory. But I don't want to manage the transactions by myself, if it's not absolutely necessary.

Upvotes: 1

Views: 1037

Answers (1)

Ravi Vasamsetty
Ravi Vasamsetty

Reputation: 413

There is some ambiguity in your statement. Are you constrained by using only one 'Persistent Unit'? It is not same as Constrained by using Single Datasource.

You can create multiple persistent units for a single datasource. So, if you are not constrained by the number of persistent units you can create, You can in persistence.xml declare 2 persistent units for the same datasource like below

<?xml version="1.0" encoding="UTF-8"?>
<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="PU1"
        transaction-type="JTA">
        <jta-data-source>jdbc/myDS</jta-data-source>
        <!-- Other properties -->
    </persistence-unit>

    <persistence-unit name="PU2"
        transaction-type="JTA">
        <jta-data-source>jdbc/myDS</jta-data-source>
        <!-- Other properties -->
    </persistence-unit>
</persistence>

Then, you can create 2 entitymanagers like below

@PersistenceContext(unitName="PU1", type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;

@PersistenceContext(unitName="PU2", type = PersistenceContextType.EXTENDED)
private EntityManager otherEntityManager;

Hope this helps.

Upvotes: 2

Related Questions