我看到的用于创建 EntityManager 的惯用语是这样的:
public class BaseDao {
private static final String PERSISTENCE_UNIT_NAME = "Employee";
EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
public EntityManager getEntityManager() {
return factory.createEntityManager();
}
}
然后它是这样使用的:
Employee emp = new Employee();
emp.setName("Joe M");
getEntityManager().persist(emp);
问题是为什么不这样做:
public class BaseDao{
private static final String PERSISTENCE_UNIT_NAME = "Employee";
EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
private EntityManager entityManager = null;
public void setEntityManger() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
this.entityManager = factory.createEntityManager();
}
public EntityManager getEntityManager() {
return this.entityManager;
}
}
换句话说,是否需要始终让实体经理通过factory.createEntityManager()
?还是可以将其创建为实例(甚至静态)变量并像那样检索?
澄清一下,我说的是不使用 EJB 或 Spring 容器的环境。
谢谢。