1

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Now it is clear for me, thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.