不幸的是,您必须手动完成。我通常这样做的方式是定义一个特殊的类:
public class EMF {
private static EntityManagerFactory factory = Persistence.createEntityManagerFactory("name");
public static EntityManager getEntityManager() {
return factory.createEntityManager();
}
}
因此,每次您需要 EntityManager 时,您都必须手动创建它。您还需要处理事务:
EntityManager em = EMF.getEntityManager();
EntityTransaction et = em.getTransaction();
try {
MyEntity my = new MyEntity();
et.begin();
try {
em.persist(my);
et.commit();
} catch (Exception ex) {
if (et.isActive())
et.rollback();
}
} finally {
em.close();
}