session.Merge和session.SaveOrUpdate有什么区别? [英] What's the difference between session.Merge and session.SaveOrUpdate?

查看:77
本文介绍了session.Merge和session.SaveOrUpdate有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到有时与父/子对象或多对多关系,我需要调用SaveOrUpdateMerge.通常,当我需要调用SaveOrUpdate时,我在调用Merge时遇到的异常与未首先保存临时对象有关.

I notice sometimes with my parent/child objects or many-to-many relationships, I need to call either SaveOrUpdate or Merge. Usually, when I need to call SaveOrUpdate, the exception I get on calling Merge has to do with transient objects not being saved first.

请说明两者之间的区别.

Please explain the difference between the two.

推荐答案

这来自

saveOrUpdate()执行以下操作:

saveOrUpdate() does the following:

  • 如果对象在此会话中已经存在,则不执行任何操作
  • 如果与会话相关联的另一个对象具有相同的标识符, 引发异常
  • 如果对象没有标识符属性,请保存()
  • 如果对象的标识符具有分配给新对象的值 实例化的对象,将其保存()
  • 如果对象是版本化的(通过< version>或< timestamp>),并且 版本属性值与分配给新属性的值相同 实例化的对象,将其保存()
  • 否则update()对象
  • 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

和merge()非常不同:

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

如果您尝试更新从会话分离的某一时刻的对象,则应该使用Merge(),特别是如果当前存在与会话相关联的那些对象的持久实例.否则,在这种情况下使用SaveOrUpdate()会导致异常.

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.

这篇关于session.Merge和session.SaveOrUpdate有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆