Suppose we have two entities dependant to each other and DAOs for each of them
Entity1 -> * Entity2
Entity2
now suppose we have two threads that are pulling some data from database, Thread1 asks Entity1Dao to get some object with dependant fields initialized, meanwhile Thread2 tries to get same Entity2 objects (already retrieved) with Entity2Dao.
Entity1Dao creates EntityManager (em1) and retrieves data, and Entity2Dao will create different EntityManager (em2) to get queries objects from database.
QUESTION: Does em2 stay locked until em1 get closed? if not should we get exception on "other entitymanager containing requested object"?
No. Every EntityManager will return different instances of the entities.
The concurrent transactions will then, potentially, write to the same rows, and the last one will win, unless you implement optimistic concurrency (by adding an @Version field to your entities).
The entity managers are totally independent in this case. There are mechanisms of optimistic locking and pessimistic locking offered by JPA that you could use to coordinate what should happen during two transaction dealing with the same data.
See the JPA 2.1 Specification, section 3.4 about Locking and Concurrency.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With