19

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?

Tiny
  • 24,933
  • 92
  • 299
  • 571
Yatendra
  • 31,339
  • 88
  • 211
  • 291

1 Answers1

12

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.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • For Q1: I guess an _Entity Manager_ object should have minimal overhead, but I'm still itching to ask how much overhead :) Wow, that diff threads that depends on each other is more complex. So is it safe to say that you should have 1 EM per Thread? Then you make sure that you catch any exceptions since you have multiple threads using the same table, right? – thirdy Dec 28 '11 at 04:34
  • Yes since EM is not thread safe , can it be used across multiple threads if I create a wrapper around it and include 'synchronized' save/update methods in the wrapper which internally call save/update of EM. Also i never clear/close the EM ? I think there can still be issues for simultaneous read and write. Could you please let me know your comments on this ? – bluelurker May 06 '16 at 17:56