What's the difference between session.Merge and session.SaveOrUpdate?
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.
As I understand it, merge()
will take an object that may not be associated with the current session, and copy its state (property values, etc.) to an object that is associated with the current session (with the same PK value/identifier, of course).
saveOrUpdate()
will call Save or Update on your session, based on a given object's identity value.
SaveOrUpdateCopy()
is now deprecated as of NHibernate 3.1. Merge()
should be used instead.
** Update()**
:- if you are sure that the session does not contains an already persistent instance with the same identifier then use update to save the data in hibernate
** Merge()**
:-if you want to save your modifications at any time with out knowing about the state of an session then use merge() in hibernate.