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 ?
Yes, and by the way - this is exactly what @PersistenceContext
will do. It will:
EntityManager
once @Transactional
is invoked (or in case OpenEntityManagerInViewFilter
is set up - when the filter is invoked)@Transactional
method (or out of the filter) - it will close the EntityManager