I am currently obtaining an EntityManager from the EntityManagerFactory within the doFilter method of a servlet Filter, passing it to the Servlet, and closing it on the way out.
Is this good practice as far as the lifetime of EntityManager is concerned? Or should I have a different lifetime for EntityManager?
Sounds good to me.
Filters and servlets will be used by multiple threads at once (unlike stateless or statefull EJB). So the
EntityManagershould be looked up per request.Alternatively, you can force the web container to synchronize accesses to servlets (not sure for filters) by specifying that the
SingleThreadModelis desired, in which case you could inject theEntityManageronce for all in your filter or servlet.The information above come from this post about PersistenceContext in a web app.
Obtaining an
EntityManageris I believe a cheap operation (unlike obtaining the factory itself). At least, that was the case with Hibernate’s Session and SessionFactory. So I would go for your original design.