Wednesday, 6 April 2016

What are detached objects and how to handle them ?


Detached objects

When we close the session, the persistent objects associated with session are detached
Means :
  • The data is still in memory of application.
  • Hibernate is no longer responsible for tracking changes to the objects.

If we then modify our detached object and want to update it, we have to reattach the object. 

When you call saveOrUpdate() or just update() on a detached object, Hibernate throws NonUniqueObjectException.
There may be multiple copies modified and Hibernate doesn't know the latest one (as it doesn't have track of detached objects), so it throws NonUniqueObjectException.

We can avoid this exception, by calling merge() instead of saveOrUpdate() or save() method on detached objects.
merge() will merge all the changes in memory before the save.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.