Skip to main content

Hibernate session.merge(persistingObject) Vs session.saveOrUpdate(persistingObject)

Hibernate provide two techniques to deal with save and update functionality,
As per those techniques it first checks the instance in db, if
It is already persisted in that database, if that is the case then it
will simply persist the updated fields into DB otherwise it will persist
the new instance in to DB.

session.saveOrUpdate(persistingInstance):It also persist the new instance in to DB
and update the already persisted instances.
Insert the data if the primary key is not exist.

Problem:In some scenario's you might face the issue of
NonUniqueObjectException : message
"a different object with the same identifier value was
already associated with the session."

Technically before persisting in to db it first check in to the Hibernate cache,
and by any reason if that
object is present in cache then you will get the above exception.

So by remedy of the above issue we can use session.merge(persistingObject):
It is directly checking in to your database not in Hibernate cache,
so the above error will never ever arise.

Recommendation
:session.merge();

Comments

Popular posts from this blog

Sorting an List in Java

// Create a list String[] strArray = new String[] {"z", "a", "C"}; List list = Arrays.asList(strArray); // Sort Collections.sort(list); // C, a, z // Case-insensitive sort Collections.sort(list, String.CASE_INSENSITIVE_ORDER); // a, C, z // Reverse-order sort Collections.sort(list, Collections.reverseOrder()); // z, a, C // Case-insensitive reverse-order sort Collections.sort(list, String.CASE_INSENSITIVE_ORDER); Collections.reverse(list); // z, C, a

Hibernate

Best sites which are very much useful for assist in Hibernate related problems * Hibernate main site * Hibernate Tutorial * Hibernate Forum * Hibernate Wikipedia * Popular Hibernate Books * Hibernate Materials * Relational Persistence for Idiomatic Java