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();
}
}
Then it is used like this:
Employee emp = new Employee();
emp.setName("Joe M");
getEntityManager().persist(emp);
Question is why not do it this way:
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;
}
}
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?
To clarify, I am talking about an environment that doesn't use EJB or Spring containers.
Thanks.
Best Solution
There are two ways to create
EntityManager
instances.One way is for SDK applications, and I use this way a lot in unit testing. This is what you have in your example:
In Enterprise applications you let the container create them for you and inject them when needed.
EntityManager
is just a wrapper around a JDBC connection. It's very light weight and can be created and destroyed without performance penalty.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):
Once you get this protoyped and ready, you can use a generic DAO.