62

What is the difference between SaveOrUpdate and Save/Update in NHibernate. Why wouldnt you just always use SaveOrUpdate? Also, what is the point of SaveOrUpdateCopy?

1 Answers1

76

Chapter 9 covers all of this better than I can:

http://nhibernate.info/doc/nh/en/index.html

But cliff notes:

Save() takes a new object without an identifier and attaches it to the session. The object will be INSERT'd.

Update() takes an existing object that has an identifier but is not in the session and attaches it to the session. The object will be UPDATE'd.

SaveOrUpdate() looks at the identifier and decides what is necessary in the above.

SaveOrUpdateCopy() is special in that say you have two objects with the same identifier -- one in the session and one not. If you try and update the one not in the session an exception is thrown normally (you are now trying to attach two objects that represent the same persistent object to the session). SaveOrUpdateCopy() copies the non-session object state to the session object state.

I'm not sure how you are going to use NH, but for a lot of cases all you need is Save(). The session is doing ALL of the work necessary to know what has to be updated and simply Flush() or a Commit() does everything you need.

hazzik
  • 13,019
  • 9
  • 47
  • 86
anonymous
  • 6,825
  • 8
  • 47
  • 60
  • 2
    You usually don't need SaveOrUpdate() because NHibernate tracks changes to every loaded object. To update an object use Session.Get(), make you change then call Session.Flush(). – Brian Low Nov 30 '10 at 21:49
  • What is more readable or intention revealing in the code then: `SaveOrUpdate()` or `Flush()` / `Commit()`? Or does it not make a difference (semantic or otherwise)? – Matt Kocaj Jul 19 '12 at 09:05
  • Explicitly flushing your session is probably not necessary. If you commit a transaction or the session goes out of scope/is disposed of the changes will automatically be persisted (or earlier if they need to be for some reason, id generation or the like). Flush is intention-revealing (to me) when you *need* to force the changes automatically, because of read-ioslation or some other esoterica, and just noise otherwise. Anyone familiar with NH will understand the implicit `Update` for attached entities as well, so I tend to the think the same of explicit `SaveOrUpdate` statements as well. – Matt Enright Sep 18 '13 at 13:47
  • see this quesion also, http://stackoverflow.com/questions/161224/what-are-the-differences-between-the-different-saving-methods-in-hibernate – aeliusd Sep 04 '14 at 07:35
  • 3
    tried to edit but the edit was rejected. Anyways, the behaviour on `Save`is incorrect in the answer. `Save` will either `insert`or `update`as needed. `update`however will throw an exception if trying to save an entity that doesn't exist yet. – aeliusd Sep 04 '14 at 11:02
  • @MattEnright you need to `Flush()` if you are not using transaction – Sebastian Xawery Wiśniowiecki Apr 27 '15 at 11:32