12

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?

petertc
  • 3,607
  • 1
  • 31
  • 36
user2198754
  • 185
  • 3
  • 6

2 Answers2

12

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).

James
  • 17,965
  • 11
  • 91
  • 146
  • 1
    When using first approach, sometimes EntityManager is not in 'sync' because `ThreadLocal` will spawn new EntityManager for each thread. I've left with only one choice: to create a new EntityManager per transaction. – user2198754 Apr 29 '13 at 18:54
  • 1
    James Sutherland recommends that reuse EntityManager during request. The main reason is persistence context sharing. Do you agree that? http://www.coderanch.com/t/550734/ORM/databases/Practise-EntityManager – petertc Sep 09 '15 at 14:39
3

The link provided by okwap is very helpfull. To make sure it will not slip through, and to follow the board rules, I put 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 that, I will add, that reading through two different EntityManager may even give objects with different content, if a database transaction was performed by someone else in the meantime. But if reading repeatedly through the same entitymanager, the 2nd read wil just get the objet from the entitymanager cache, so the newer state wil just not be visible.

Thomas Schütt
  • 832
  • 10
  • 14