我正在开发一个 spring-hibernate-envers 应用程序。经过大量谷歌搜索,事情终于对我有用了,但我仍然有几个问题。
早些时候我使用
saveOrUpdate
保存或更新实体。但 与envers一起工作时 抛出一个nonUniqueObject
异常(exception)。所以我改用merge
它奏效了。使用是否正确 为此合并?merge
是否插入 数据库的新对象?我尝试了以下代码:
entity=merge(entity); saveOrUpdate(entity);
这也奏效了。这是正确的方法吗?而且我很好奇为什么 saveOrUpdate
现在没有抛出任何错误。
最佳答案
saveOrUpdate() does the following:
- 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 or , and the version property value is the same value assigned to a newly instantiated object, save() it
- otherwise update() the object
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
这意味着如果您确定具有相同标识符的对象未与 session 相关联,则可以使用saveOrUpdate()
。否则你应该使用 merge()
。
下面的代码
entity=merge(entity);
saveOrUpdate(entity);
之所以有效,是因为 merge()
的结果是一个持久对象,因此它会被 saveOrUpdate()
忽略,因此第二行没有任何意义。
关于java - hibernate envers : merge & saveOrUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5311928/