I am trying to get an instance of jpa EntityManager in a servlet as follows
ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
EntityManagerFactory emf = (EntityManagerFactory)context.getBean("entityManagerFactory");
EntityManager em=emf.createEntityManager();
My question is , is it an efficient way to get an EntityManager instance inside a servlet get service method. Also should we close EntityManagerFactory/EntityManager explicitly in the above approach.
Since you are using spring, ideally you should use another layer (DAO for example) where you can have
And spring will take care of that.
If you really need that access in a servlet, rather than in a spring-mvc
@Controller, then get the service/dao bean from the application context and use the above construct there. And if for some weird reason you should manually handle the entity manager – yes, you have to.close()it.