create EntityManager from EntityManagerFactory
I am trying to get an instance of jpa EntityManager in a servlet as follows
Appli开发者_如何学运维cationContext 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
@PersistenceContext
private EntityManager entityManager;
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.
加载中,请稍侯......
精彩评论