NonUniqueObjectException- a different object with the same identifier value was already associated with the session

9 years ago

If you are developing in Swing and using hibernate you might - at some point in time - run into this exception: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

What happened, you might ask? Well, turns out that when you close the session that created a given hibernate-managed object, this object becomes "detached" (meaning hibernate no longer has any control over it). So, when you attempt to save or update it in another session, hibernate will complain with that exception, because it can no longer tell which is the "true" version of the object.

The solution(s)? Look inside your code for places where you might be closing the session and take that out. That's the solution in the case where you are using a long session (one that spans the entirety of the application's life). In case you really want to close the session, you might consider using the session's merge() method, which basically merges the fields in both the attached and non-attached instances of the object, and performs an update.

Hope that saves someone half a day of debugging ;)