When we need more than one EntityManager?

Yatendra picture Yatendra · Apr 6, 2010 · Viewed 8k times · Source

I am learning JPA and have one question:

In which situations we need more than one EntityManager in our application?

The two situations that I am aware of are as follows:

  • When our application is a multi-threaded application and more than one thread needs JPA transaction because EntityManager is not thread-safe and we need one EntityManager per thread.

  • When any of the thread needs multiple concurrent transactions, we need more than one EntityManager in that thread because there is one-to-one relationship between EntityManager and EntityTransaction.


Q1. Are there any other situations when we need more than one EntityManager?

Q2. Upto my understanding, there should be only one EntityManagerFactory per Persitence Unit. Am I correct? If not, then what are those situations when we need multiple EntityManagerFactory per Persistence Unit?

Answer

BalusC picture BalusC · Apr 6, 2010

Q1: The EntityManager is best to be compared with the "good old" Hibernate Session: an unit of work (a simple business action, e.g. "logging in an user", "placing an order", etc). It is not necessarily tied to a single thread. You will only run in trouble if the different threads execute DB tasks which depends on each other inside a single unit of work. You would need to execute them in sync (preferably, in order in a single thread). If you for example have the business requirement to clean up some "old logs" when an user logs in (which reasonably wouldn't disturb each other's information), you can perfectly execute it in two separate threads inside a single unit of work.

Q2: Your understanding is correct. You can however create more than one, but that wouldn't make any sense nor have any benefits. It would only add significant overhead.