Search code examples
jpajpa-2.0entitymanager

Reusing entity manager by em.clear() or creating a new entity manager?


In my case of application managed transaction, I've to choose between:

  1. Using one single EntityManager and calling clear() before each new transaction. Share the EntityManager using a ThreadLocal.
  2. Creating a new EntityManager for each transaction.

I don't have much experience on JPA. My question is which one is better in terms of performance?


Solution

  • I would recommend creating a new EntityManager per transaction. This is the way JPA was designed. The EntityManager should not be an expensive object to create. (the EntityManagerFactory is very expensive though, so ensure you only have one of those).