获取EntityManager的不同方法 [英] Different ways of getting the EntityManager
问题描述
我看到的用于创建EntityManager的惯用法是这样的:
The usual idiom I see for creating the EntityManager is something like this:
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()
获取实体管理器?还是可以将其创建为实例(甚至是静态)变量并像这样进行检索?
In other words is there a need to always get the entity manager through factory.createEntityManager()
? or can it be created as an instance (or even static) variable and retrieved like that?
为澄清起见,我正在谈论的是不使用EJB或Spring容器的环境.
To clarify, I am talking about an environment that doesn't use EJB or Spring containers.
谢谢.
推荐答案
有两种创建EntityManager
实例的方法.
There are two ways to create EntityManager
instances.
一种方法是用于SDK应用程序,在单元测试中,我经常使用这种方法.这就是您的示例中的内容:
One way is for SDK applications, and I use this way a lot in unit testing. This is what you have in your example:
EntityManagerFactory factory =
Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
在企业应用程序中,您可以让容器为您创建它们,并在需要时注入它们.
In Enterprise applications you let the container create them for you and inject them when needed.
EntityManager
只是JDBC连接的包装.它的重量很轻,可以创建和销毁而不会降低性能.
EntityManager
is just a wrapper around a JDBC connection. It's very light weight and can be created and destroyed without performance penalty.
请记住,EntityManager
并非线程安全的,因此,如果您有一个实例,则可能需要同步对其的访问.参见交易基础了解详情.
Keep in mind that the EntityManager
is not thread safe, so if you have one instance, you may need to synchronize access to it. See transaction basics for details.
这是我大致的处理方式:
Here's how I would do it (roughly):
public class BaseDao{
private static final String PERSISTENCE_UNIT_NAME = "Employee";
private static EntityManagerFactory factory =
Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
public void create(MyEntiy person){
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
// do what ever you need
em.getTransaction().commit();
em.close();
}
// add more methods to the dao.
}
一旦您将此原型制作好并准备就绪,就可以使用通用DAO.
Once you get this protoyped and ready, you can use a generic DAO.
这篇关于获取EntityManager的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!