persistenceContext link 如何与多个 EntityManager

How can a persistenceContext link with multiple EntityManager

最近我浏览了 PRO JPA2 这本书,发现 "A single persistence context can be link with multiple EntityManager instance."

我已经搜索过相同的但找不到满意的答案。有人可以举例说明吗?

如果没有书中的更多上下文,很难准确了解其含义。也就是说,如果您在全局事务中使用容器管理的 JPA,那么每个引用相同持久性单元的注入 EntityManager 都将由相同的持久性上下文支持。例如:

@Stateless
public class Bean {
    @PersistenceContext
    EntityManager em1;

    @EJB
    OtherBean otherBean;

    @TransactionAttribute(REQUIRED) // The type, but for illustration
    public void doWork() {
        // ... use em1
        otherBean.doMoreWork();
    }
}

@Stateless
public class OtherBean {
    @PersistenceContext
    EntityManager em2;

    public void doMoreWork() {
        // ... use em2, it shares a persistence context with em1
    }
}