开发者

create EntityManager from EntityManagerFactory

开发者 https://www.devze.com 2023-04-04 02:52 出处:网络
I am trying to get an instance of jpa EntityManager in a servlet as follows Appli开发者_如何学运维cationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消