何时应创建/打开 EntityManagerFactory 实例?
2022-09-01 15:13:42
好的,我阅读了一堆关于如何在单例中编写实体管理器工厂的文章/示例。
其中一个对我来说最容易理解:
http://javanotepad.blogspot.com/2007/05/jpa-entitymanagerfactory-in-web.html
我了解到EntityManagerFactory(EMF)应该只在应用程序范围内创建一次。
还要确保在使用EMF后将其关闭(?
所以我编写了EMF帮助器类供业务方法使用:
public class EmProvider {
private static final String DB_PU = "KogaAlphaPU";
public static final boolean DEBUG = true;
private static final EmProvider singleton = new EmProvider();
private EntityManagerFactory emf;
private EmProvider() {}
public static EmProvider getInstance() {
return singleton;
}
public EntityManagerFactory getEntityManagerFactory() {
if(emf == null) {
emf = Persistence.createEntityManagerFactory(DB_PU);
}
if(DEBUG) {
System.out.println("factory created on: " + new Date());
}
return emf;
}
public void closeEmf() {
if(emf.isOpen() || emf != null) {
emf.close();
}
emf = null;
if(DEBUG) {
System.out.println("EMF closed at: " + new Date());
}
}
}//end class
我使用EmProvider的方法:
public String foo() {
EntityManager em = null;
List<Object[]> out = null;
try {
em = EmProvider.getInstance().getEntityManagerFactory().createEntityManager();
Query query = em.createNativeQuery(JPQL_JOIN); //just some random query
out = query.getResultList();
}
catch(Exception e) {
//handle error....
}
finally {
if(em != null) {
em.close(); //make sure to close EntityManager
}
//should I not close the EMF itself here?????
EmProvider.getInstance().closeEmf();
}
我确保按照建议在方法级别内关闭 EntityManager (em)。但是,EntityManagerFactory什么时候应该关闭呢?为什么EMF必须如此糟糕???我阅读了有关并发问题的信息,但由于我没有多线程语法的经验,因此我无法真正清楚地了解这个想法。