What is a detached object ?
When we close an individual Hibernate Session, the persistent objects we are working with are detached. This means the data is still in the application’s memory, but Hibernate is no longer responsible for tracking changes to the objects.
Reattachment of detached object
If we then modify our detached object and want to update it, we have to reattach the object.
During that reattachment process, Hibernate will check to see if there are any other copies of the same object, which may lead to bad data.
Rather than save possibly bad data, Hibernate tells us about the problem via the NonUniqueObjectException , when saveOrUpdate() or update() is called on a detached object.
Avoid NonUniqueObjectException using merge
In Hibernate 3, we have merge() method which forces Hibernate to copy any changes from other detached instances onto the instance you want to save, and thus merges all the changes in memory before the save.
Example
/*** Txn 1 ***/
Session session = sessionFactory1.openSession();
Transaction tx = session.beginTransaction();
Item item = (Item) session.get(Item.class, new Long(1234));
tx.commit();
session.close(); // End of first session, "item" is detached
item.getId(); // The database identity is "1234"
item.setDescription("my new description"); // Update on detached object
/*** Txn 2 ***/
Session session2 = sessionFactory.openSession();
Transaction tx2 = session2.beginTransaction();
Item item2 = (Item) session2.get(Item.class, new Long(1234));
// Suspecting more than one copy of item object, so exception occurs
// session2.update(item); // Throws NonUniqueObjectException
// No problem (error) when using merge
Item item3 = session2.merge(item); // Success, No exception
tx2.commit();
session2.close();
merge() returns a reference to the newly updated version of the instance.
It isn’t reattaching item to the Session.
If you test for instance equality (item == item3), you’ll find it returns false in this case.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.