Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate. When does same entity may be loaded twice in one session?

Tags:

java

hibernate

Having such problem. Loaded collection of 2 objects (by primary key, using criteria). Then iterating them in the loop. When processing first object, somewhere very very far from this loop, is loaded object by same primary key as second object in loop. Here I see that System.identityHashCode() are different for this 2 objects. When processing second object from loop and trying to save it I get exception:

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:

Trying to simulate this problem with simple object, loading , modifying, once more loading by PK, saving with different transaction propogation-s I always get same object instance... Could you please tell when it is possible to get second object instance in same session loading by PK?

like image 422
whatswrong Avatar asked Dec 16 '13 08:12

whatswrong


1 Answers

In my situation problem was because: Firstly I have loaded some entity 'A' by primary key. Then I have loaded another entity 'B' using some criteria which through hbm mapping referenced this same (by PK) entity 'A' (for example B->some entity C->A) and hibernate didn't use already loaded 'A' entity, but loaded or created it secondly (I put breakpoint in entity 'A' constructor), thus in single session we have 2 entities with same PK but different instances. Trying to save entity 'A' we get exception 'NonUniqueObjectException'. Loading entity 'B' was somewere very very far away and under some conditions to reproduce and identify the problem. To find such places faster easily put breakpoint in 'NonUniqueObject' constructor and find who is loading this entity second time. By the way after I loaded entity 'B' I didn't try to call B->C->A, lazy='proxy' or without lazy at all, which means load C per request. Some mysteries to me...

like image 51
whatswrong Avatar answered Oct 14 '22 10:10

whatswrong