1

I wonder what is the difference between Save() and SaveOrUpdate() methods in nHibernate, and what I right know is that the main difference is that:

Save()

  • return id of a saved entity
  • simply saves an entity (without update?)

SaveOrUpdate()

  • doesn't return an id of a saved entity

  • Invokes Save() (if entity doesn't exist in db), or invokes Update() (if entity exists)

But my question is that, is Save() in nHibernate is similar to Save() in java Hibernate? Because if I want to write simple function, which will save entity and return me only the id of an already saved entity. I should write function like that:

public int ReturnMeAnIdOfSavedEntity(IEntity ent)
{
    _session.SaveOrUpdate(ent);
    return ent.Id;
}

or I can write function like that:

public int ReturnMeAnIdOfSavedEntity(IEntity ent)
{
    return (int)_session.Save(ent);
}

I also found questions and blogs about Save() but in Hibernate, not in NHibernate, so I'm not 100% right if the function play similar.

Related question/blogs

Thanks for answers!

Community
  • 1
  • 1
MNie
  • 1,347
  • 1
  • 15
  • 35

1 Answers1

4

It's been a while since I used NHibernate, but from what I remember

  • Save - does the equivalent of Insert
  • Update - does the equivalent of Update

You would use SaveOrUpdate if you have a collection of objects, some of which are new and others of which were read from the DB and may or not have been changed to enumerate the collection once and make sure that the changes are sent to the DB:

foreach(var customer in customers) { session.SaveOrUpdate(customer); }

To save you doing something like this:

foreach(var customer in customers)
{
    if(customer.Id == 0) { session.Save(customer); }
    else { session.Update(customer); }
}
Trevor Pilley
  • 16,156
  • 5
  • 44
  • 60
  • Thanks for an answer! I only want to know if Save also invokes Update() when invoking on an already existing entity in db. So I suppose it rather throw an error instead of invoke Update() (depending on Your answer). – MNie Sep 08 '15 at 10:14