Greg
Greg

Reputation: 147

create EntityManager from EntityManagerFactory

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.

Upvotes: 2

Views: 2802

Answers (1)

Bozho
Bozho

Reputation: 597106

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.

Upvotes: 4

Related Questions