7

What are the differences between Hibernate Session methods saveOrUpdate(Object) and merge(Object)? It seems that both methods generate an SQL INSERT statement when the given object does not exist in the corresponding table and an UPDATE when it does exist.

Derek Mahar
  • 27,608
  • 43
  • 124
  • 174
  • 1
    Did you actually read the java docs you linked to? :) – willcodejavaforfood Dec 16 '10 at 15:32
  • Yes, I did. The main difference that I see is that `merge()` loads an object that is not in the session while `saveOrUpdate()` does not. Does this mean that `saveOrUpdate()` of a partial object overwrites all fields while `merge()` overwrites only those fields that have been set to non-null values? Or do both produce the same result? – Derek Mahar Dec 16 '10 at 15:44
  • possible duplicate of [NHibernate - Difference between session.Merge and session.SaveOrUpdate?](http://stackoverflow.com/questions/170962/nhibernate-difference-between-session-merge-and-session-saveorupdate) – Brant Bobby Feb 21 '13 at 20:52

3 Answers3

1

Even though this is for NHibernate, it also applies to Hibernate:

NHibernate - Difference between session.Merge and session.SaveOrUpdate?

Community
  • 1
  • 1
jpkroehling
  • 13,881
  • 1
  • 37
  • 39
  • According to the third comment, NHibernate `Merge()` and `SaveOrUpdate()` produce exactly the same result. (The commenter states that `SaveOrUpdate()` simply delegates to `Merge()`.) – Derek Mahar Dec 16 '10 at 16:10
  • 1
    Ok, if this is true, than it's not the same for Hibernate :-) Both calls *may* produce the same result, but depends on the state of the entity. Instead of replicating the documentation, I'll provide just the updated link :-) http://docs.jboss.org/hibernate/core/3.5/reference/en/html/objectstate.html#objectstate-saveorupdate – jpkroehling Dec 16 '10 at 16:15
1

If I remember correctly, merge is for un-associated instances, that aren't currently managed. It will do a lookup based on id and merge the two.

Scott
  • 338
  • 2
  • 13
  • What does it mean to "merge the two" objects? How does it know which fields to merge? Does it merge only those that do not differ or those that differ and are non-null? The first case is no different from an update while the second differs from both save and update. – Derek Mahar Dec 16 '10 at 15:47
  • Look at the second answer on the linked question that quotes the spec. 3.2.4.1 - http://stackoverflow.com/questions/3870844/best-approach-for-updation-using-jpa It looks like the detached instance will overwrite most of the data, unless a field is marked lazy or the class supports versions. – Scott Dec 16 '10 at 17:57
1

SaveOrUpdate versus Merge in Hibernate explains the differences between saveOrUpdate() and merge().

Derek Mahar
  • 27,608
  • 43
  • 124
  • 174