java - hibernate envers : merge & saveOrUpdate

标签 java hibernate hibernate-envers

我正在开发一个 spring-hibernate-envers 应用程序。经过大量谷歌搜索,事情终于对我有用了,但我仍然有几个问题。

  1. 早些时候我使用saveOrUpdate 保存或更新实体。但 与envers一起工作时 抛出一个 nonUniqueObject 异常(exception)。所以我改用 merge 它奏效了。使用是否正确 为此合并? merge 是否插入 数据库的新对象?

  2. 我尝试了以下代码:

entity=merge(entity);  
saveOrUpdate(entity);

这也奏效了。这是正确的方法吗?而且我很好奇为什么 saveOrUpdate 现在没有抛出任何错误。

最佳答案

Hibernate Reference说:

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/

相关文章:

java - 如何通过搜索某些字符从另一个字符串创建子字符串

java - 如何查找 Java String 是否包含 X 或 Y 并包含 Z

java - 来自数据库的 JSP 下拉列表

java - Hibernate:尝试获取锁时发现死锁

java - Hibernate envers spring web app如何记录用户名

java - android studio 如何解决无法解析: play-services-basement?

java - Hibernate 4.1 到 5.1 SessionFactory ConnectionProvider

java - Spring 数据休息 : Expose new endpoints for Repository that extends Revision Repository

java - 恩弗斯 & "A different object with the same identifier value was already associated with the session"

java - 您如何模拟 JavaFX 工具包初始化?