且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java EE应用程序中处理多个EntityManager

更新时间:2023-11-19 21:16:04

容器管理的实体管理器会自动传播当前的JTA事务和 EntityManager 映射到同一持久性单元的引用提供对该事务中持久性上下文的访问。因此,除了并发问题之外,从单例共享实体管理器并不是一个好习惯,这会导致为您在bean上调用的每个方法使用相同的事务上下文。

一个简单的解决方案来满足您的需求是在bean中注入 EntityManagerFactory 引用并创建 EntityManager 对象调用 createEntityManager()方法。
缺点是您应该手动管理事务,不再依赖容器。

否则,另一种方法可能是将所有实体管理器注入主企业bean并在服务中实现业务逻辑bean使用您传递适当管理器的方法。
后一种解决方案的一个例子:

Container managed entity managers are automatically propagated with the current JTA transaction and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. So it's not good practice to share an entity manager from a singleton, apart from concurrency problems, it would result in using the same transaction context for every method you call on your beans.
A simple solution to your need is to inject EntityManagerFactory references in your beans and create EntityManager objects calling the createEntityManager() method. The drawback is that you should manage transactions manually, no more relying on the container.
Otherwise another approach could be inject all of your entity managers in a main enterprise bean and implement business logic in service beans with methods to which you pass the appropriate managers. An example of the latter solution:

@Stateless
class MainBean {
    @PersistenceContext EntityManager em1;
    @PersistenceContext EntityManager em2;
    ...
    @EJB WorkerBean1 workerBean1;
    @EJB WorkerBean2 workerBean2;
    ...
    void method1(Object param1, Object param2) {
        workerBean1.method1(em1, param1, param2);
    }

    void method2(Object param1, Object param2, Object param3) {
        workerBean2.method2(em2, param1, param2, param3);
    }
    ...
}

@Stateless
class WorkerBean1 {
    void method1(EntityManager em, Object param1, Object param2) {
        ...
    }
    ...
}

@Stateless
class WorkerBean2 {
    void method2(EntityManager em, Object param1, Object param2, Object param3) {
        ...
    }
    ...
}