gpt4 book ai didi

java - JPA 当我应该关闭实体管理器时

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:57 25 4
gpt4 key购买 nike

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

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();
}

}

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

最佳答案

回答你的问题我认为最好的方法是使用我所附的图像: entitymanager

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

关于java - JPA 当我应该关闭实体管理器时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com