【问题标题】:JPA when I should close entity manager当我应该关闭实体管理器时的 JPA
【发布时间】:2016-10-05 11:35:06
【问题描述】:

什么时候应该关闭实体管理器?

public TYPE getItem(Long id) {
        if (id != null) {
            try {
                em = EMFactory.createEntityManager();
                TYPE item=em.find(entityClass, id);
                return item;
            } catch (Exception e) {
                System.err.println(e.getMessage());
            } finally {
                if (em != null)
                    em.close();
            }
        }
        return null;
    }

@WebListener
public class EMFactory implements ServletContextListener {

    private static EntityManagerFactory emf;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        emf = Persistence.createEntityManagerFactory("ejb");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        emf.close();
    }

    public static EntityManager createEntityManager() {
        if (emf == null) {
            emf = Persistence.createEntityManagerFactory("ejb");
          // throw new IllegalStateException("Context is not initialized yet.");
        }

        return emf.createEntityManager();
    }

}

我总是在任何操作创建/更新/选择/删除后关闭实体管理器。但我想这不是效率。那么应该如何实现呢?

【问题讨论】:

    标签: java jpa entitymanager


    【解决方案1】:

    如果您在应用启动/停止时使用long-lived-transactions,否则在会话激活/钝化/创建时使用。

    【讨论】:

      【解决方案2】:

      回答您的问题我认为最好的方法是使用我附上的图片:

      但是您可能应该利用 Java EE 和 EJB 可以为您提供的所有优势,您可以拥有一个容器来管理您所经历的所有麻烦。它根据您的客户端会话的需要在后台处理 entitymanagerfactory。 看一眼 http://docs.oracle.com/javaee/6/tutorial/doc/bnblr.html

      【讨论】:

        猜你喜欢
        • 2016-08-27
        • 2019-03-16
        • 2016-01-08
        • 2016-07-04
        • 2016-02-10
        • 2018-03-27
        • 2015-06-22
        • 2014-09-06
        • 1970-01-01
        相关资源
        最近更新 更多