Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 915
user2198754 Avatar asked Apr 22 '13 04:04

user2198754


2 Answers

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.

like image 85
user2081279 Avatar answered Sep 21 '22 16:09

user2081279


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

like image 23
James Avatar answered Sep 21 '22 16:09

James