简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM