I have an EntityManagerFactory
for which I can create one (or multiple) EntityManager
instances. I'm using a Servlet environment, and I've got one EntityManagerFactory wired up to the servlet (via the servlet context) which is shared for the lifetime of the servlet (and therefore, for all users).
I can do one of the following:
doGet
method)Which is most appropriate? Is the cost of creating an EntityManager significant? If I do a single shared EntityManager, is there a single transaction scope (i.e. updates between independent users could commit others changes)?
You close it when you no longer need the entities in its context.
Basically, there are two types of EntityManager: Container-Managed and Application-Managed.
An EntityManagerFactory is constructed for a specific database, and by managing resources efficiently (e.g. a pool of sockets), it provides an efficient way to construct multiple EntityManager instances for that database.
While using the Java SE environment, we can use the bootstrap class called Persistence and invoke the createEntitymanagerFactory() method, which returns an instance of EntityManagerFactory for a specific persistence unit. EntityManagerFactory emf = Persistence . createEntityManagerFactory("BooksPU");
One EM for the whole servlet doesn't sound good. If you're not using container-managed EM's (for example EJB3) then the recommentation is to use an EM for a particular unit of work.
In a web application context your third suggestion (one per HTTP request) sounds good. However this may lead you down a pitfall where you are tying your service layer with your db layer (your service layer shouldn't even be aware of the existance of an EM).
Another approach would be to programatically demark transactions in your DAO and get your DAO to use a new EM for for every method call.
Edit: EMs are cheap to create as opposed to EMFs which have a significant overhead. Using one EMF (which it appears that you do) and lots of EMs is the way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With