NHibernate: How is identity Id updated when saving a transient instance?

后端 未结 4 912
我在风中等你
我在风中等你 2021-01-14 08:32

If I use session-per-transaction and call:

session.SaveOrUpdate(entity) corrected:
session.SaveOrUpdateCopy

相关标签:
4条回答
  • 2021-01-14 09:15

    I noticed I saved by calling:

    session.SaveOrUpdateCopy(entity); 
    

    ..which does NOT update the Id. But by changing to:

    session.SaveOrUpdate(entity);
    

    ..the Id's of transient entity will be updated.

    I probably misunderstood the documentation (?).. Section 9.4.2 says:

    SaveOrUpdateCopy(Object o)... If the given instance is unsaved or does not exist in the database, NHibernate will save it and return it as a newly persistent instance.

    Is it just me, or does it not sound like a transient object (unsaved), will be "returned as persistent" ? Doesn't that mean with updated Id? Would appreciate a clarification how to interpret this sentence correctly (?)

    0 讨论(0)
  • 2021-01-14 09:21

    I'm not sure I understand your question. The actual saving to the database occurs when the session is flushed (e.g. by committing the transaction). Calling SaveOrUpdate() doesn't itself save the entity, it just informs the session that the entity is due to be saved when the session is flushed.

    Assuming that the ID of the entity maps to an identity field in the database and that your mapping tells NHibernate that identity is set by the database, then the ID set by the database will be set as the entity's ID when it is saved.

    0 讨论(0)
  • 2021-01-14 09:25

    As far as your question is concerned, whenever you flush your session is when your entity is persisted to the database. When saving your (new) entity, NHibernate generates the ID for you using the generator you provided.

    Keep in mind that an Identity generator is not recommended (see this post by Ayende). When you use an Identity generator, your new entity is persisted to the database when you save, even if you don't flush to the database. The reason this happens is because NHibernate needs to provide you with an ID for the entity, which it can't do without doing a roundtrip to the database.

    A better solution would be to use something like a Guid generator, or HiLo if you want 'normal' values. This way you can save your entity without actually having to do a database roundtrip, which allows you to do a lot more performance wise (batching comes to mind).

    0 讨论(0)
  • 2021-01-14 09:39

    Nhibernate will set the ID property of your entity just after SaveOrUpdate call.

    0 讨论(0)
提交回复
热议问题