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

In my case, an application-driven transaction, I have to choose between:

  • Using a single EntityManager and calling clear() before each new transaction. Share EntityManager with ThreadLocal .
  • Create a new EntityManager for each transaction.

I do not have much experience in JPA. My question is which one is better in terms of performance?

+6
source share
2 answers

I would recommend creating a new EntityManager for each transaction. That is how JPA was developed. EntityManager does not have to be an expensive object to create. (EntityManagerFactory is very expensive, so make sure you only have one of them.)

+8
source

The link provided by okwap is very useful. To make sure that it does not slip, and to follow the rules of the board, I posted a copy here:

  - an EntityManager contains a persistence context, that will track
   everything read through it, so to avoid bloated memory, you should 
   acquire a new one, or clear it at some point
 - if you read the same object through two different EntityManager you 
   will get different objects back, so will loose object identity, which 
   is something to consider 

Based on this, I will add that reading through two different EntityManager can even give objects with different content if the database transaction was performed by someone else in the meantime. But if you read several times through the same noun. The person, the second readable wil, just gets the object from the entitymanager cache, so the new state will simply not be visible.

0
source

All Articles