简体   繁体   English

容器管理的EntityManager:单个持久性单元的多个管理器?

[英]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? 是否可以通过@PersistenceContext批注?

I want to write something like the following, but don't know how to tell JPA to inject two different manager instances. 我想编写类似以下内容的内容,但不知道如何告诉JPA注入两个不同的管理器实例。

@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 因此,如果您不受可以创建的持久性单元数量的限制,则可以在persistence.xml中为同一数据源声明2个持久性单元,如下所示

<?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 然后,您可以创建2个实体经理,如下所示

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

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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