I notice sometimes with my parent/child objects or many-to-many relationships, I need to call either SaveOrUpdate
or Merge
. Usually, when I need to call SaveOrUpdate
, the exception I get on calling Merge
has to do with transient objects not being saved first.
Please explain the difference between the two.
Once save/update is done, the object DOES NOT reflect the change. The returned object reflects the changes, and it is attached to hibernate session. MERGE method offers greater flexibility when it comes to saving data objects, since you need not worry about attaching object to Session.
The Session. save() method does an INSERT to store the object into the database and return the identifier generated by the database. On the other hand, saveOrUpdate() can do INSERT or UPDATE depending upon whether object exists in database or not.
Session. merge() is used each time an object is retrieved from the cache to create a local copy of it in each Session which requests it. The cached object remains detached; only its state is moved into copies of itself that are local to individual Session objects.
Use the save() method to store new objects into the database and when you need the generated database identifier, otherwise use the persist() method. You can use saveOrUpdate() to reattach a detached object into Hibernate Session.
This is from section 10.7. Automatic state detection of the Hibernate Reference Documentation:
saveOrUpdate() does the following:
- if the object is already persistent in this session, do nothing
- if another object associated with the session has the same identifier, throw an exception
- if the object has no identifier property, save() it
- if the object's identifier has the value assigned to a newly instantiated object, save() it
- if the object is versioned (by a <version> or <timestamp>), and the version property value is the same value assigned to a newly instantiated object, save() it
- otherwise update() the object
and merge() is very different:
- if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
- if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance
- the persistent instance is returned
- the given instance does not become associated with the session, it remains detached
You should use Merge() if you are trying to update objects that were at one point detached from the session, especially if there might be persistent instances of those objects currently associated with the session. Otherwise, using SaveOrUpdate() in that case would result in an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With