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 ?
Asked
Active
Viewed 128 times
1

Chrystian Kącki
- 15
- 5
1 Answers
1
Yes, and by the way - this is exactly what @PersistenceContext
will do. It will:
- Create
EntityManager
once@Transactional
is invoked (or in caseOpenEntityManagerInViewFilter
is set up - when the filter is invoked) - Put it in ThreadLocal variables. So that any code within this thread has access to it.
- Once the execution is out of
@Transactional
method (or out of the filter) - it will close the EntityManager

Stanislav Bashkyrtsev
- 14,470
- 7
- 42
- 45
-
Now it is clear for me, thank you – Chrystian Kącki Jan 25 '22 at 02:57