NonUniqueObjectException
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.
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.
Example
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
Session session2 = sessionFactory.openSession();
Transaction tx2 = session2.beginTransaction();
Item item2 = (Item) session2.get(Item.class, new Long(1234));
// session2.update(item); // throws NonUniqueObjectException
Item item3 = session2.merge(item); // Success!
tx2.commit();
session2.close();
No comments:
Post a Comment
Note: only a member of this blog may post a comment.