Creating EntityManager using EntityManagerFactory in web application without @PersistenceContext

193 Views Asked by At

I am creating a web application with JPA. I have configured Hibernate with connection pool c3p0.
In my case it is not possible to inject EntityManager using @PersistenceContext annotation.
In Java EE documentation they say it is thread-safe to use EntityManagerFactory instance to concurrently create EntityManager instances.
So I am using one static EntityManagerFactory instance for my persistence unit in my web app and create EntityManagers using it.
But they say that EntityManagers cannot be used concurrently (not thread-safe).
So according to this I create an EntityManager instance separately per each servlet request, use it in same thread and then dispose it.
Can I do it this way ?

1

There are 1 best solutions below

1
On BEST ANSWER

Yes, and by the way - this is exactly what @PersistenceContext will do. It will:

  1. Create EntityManager once @Transactional is invoked (or in case OpenEntityManagerInViewFilter is set up - when the filter is invoked)
  2. Put it in ThreadLocal variables. So that any code within this thread has access to it.
  3. Once the execution is out of @Transactional method (or out of the filter) - it will close the EntityManager