Reputation: 673
I am Newbie to jpa Here is the scenario...I am developing a web Apllication...where
multiple users can login...
when the user1 LogOut...i am using below code...
public static void closeEntityManagerFactory() {
if (!entityManager.getTransaction().isActive()){
entityManager.getTransaction().begin();
}
entityManager.close();
emf.close();
}
Even if the user2 is loged in it throws error telling Entity Manager is closed....The
question is we should not close the EntityManager once the application is up...??? Or we
should use Multiple instance...if yes how to achive this...help will be appreciable :) :)
Upvotes: 3
Views: 1128
Reputation: 5448
The EntityManagerFactory instance is expensive to create, the EntityManager ones are not. In a Java SE web application, most cases can be handled with only one EntityManagerFactory instance.
You can initialize the EntityManagerFactory in the contextInitialized
method of a ServletContextListener and store the instance in a context attribute (context.setAttribute(key, emf)
):
public class CustomServletContextListener implements ServletContextListener {
private EntityManagerFactory entityManagerFactory;
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
entityManagerFactory = Persistence.createEntityManagerFactory("UnitName");
context.setAttribute("someKey", entityManagerFactory);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
/* Some method that cleanly destroys
* your entity manager factory */
closeEntityManagerFactory();
}
}
Later, you can retrieve the EntityManagerFactory instance using context.getAttribute("someKey")
and create EntityManager instance where needed.
Finally, in order to get your ServerContextListener implementation to work, simply register it in your web.xml
:
<listener>
<listener-class>com.company.listeners.CustomServletContextListener</listener-class>
</listener>
Note: whether you need short-lived or long-lived EntityManager instances depends on the scopes of your application. In typical web-applications, short-lived ones that span the requests are more sensible. Refer to Java Persistence with Hibernate by Bauer and King, Manning for different strategies regarding EntityManager instances. The text addresses both Hibernate and JPA in parallel.
Upvotes: 4