有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

hibernate中的java实体合并

最好的方法是什么:

我有一些实体存储为Hibernate实体,它们包含一些字段,这些字段对于单行来说需要是唯一的。因此,当我创建另一个实体时,该字段集等于已持久化的字段集,我想用新字段覆盖旧记录,否则创建新记录

实现这一目标的最佳方式是什么


共 (2) 个答案

  1. # 1 楼答案

    如果这是实体的主键,可以使用session.merge(entity)session.saveOrUpdate(entity)

    如果它是另一个唯一的约束,您必须手动处理它——首先尝试查找具有该值的实体(通过查询),如果它不存在,则保存新的约束,否则,传输所有字段(主键除外)

  2. # 2 楼答案

    使用。改为merge()

    http://www.stevideter.com/2008/12/07/saveorupdate-versus-merge-in-hibernate/

    Theory: If we then modify our detached object and want to update it, we have to reattach the object. During that reattachment process, Hibernate will check to see if there are any other copies of the same object. If it finds any, it has to tell us it doesn’t know what the “real” copy is any more. Perhaps other changes were made to those other copies that we expect to be saved, but Hibernate doesn’t know about them, because it wasn’t managing them at the time.

    Rather than save possibly bad data, Hibernate tells us about the problem via the NonUniqueObjectException.