java - 在 Hibernate 中使用 saveOrUpdate() 创建新记录而不是更新现有记录

标签 java database hibernate orm

我有一个用户类

class User { 
  int id;
  String name;
}

idUser.hbm.xml 中的原生生成器,name 是数据库中的主键。

在我的数据库中,我保存了一些关于用户的信息。

然后我想连接有关用户的信息。

例如,在我的数据库中,我有一行 INSERT INTO User VALUES ('Bill');

主.java

User bill = new User();
bill.setName("Bill");
session.saveOrUpdate(bill);

此代码总是尝试将新的 Bill 行插入表中,而不是更新现有的 Bill 行。

最佳答案

This code always trying insert bill to database , rather than update when row about Bill exists in DB...

来自 10.7. Automatic state detection 部分Hibernate 核心文档:

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 <version> or <timestamp>, and the version property value is the same value assigned to a newly instantiated object, save() it
  • otherwise update() the object

当你这样做时:

User bill = new User();
bill.setName("Bill");
session.saveOrUpdate(bill);

这个新创建的实例没有分配任何标识符值并且 saveOrUpdate()save()它,如文件所示。如果这不是您想要的,请制作 name主键。

关于java - 在 Hibernate 中使用 saveOrUpdate() 创建新记录而不是更新现有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2857490/

相关文章:

mysql - 我如何从我的另一个 WordPress 获取高级自定义字段数据?

java - Hibernate JOIN [some entity] ON unexpected token

Java Hibernate 标准平均值 : BigDecimal instead of Double

java - HTTP-POST 上的双 HTTP-Status header 到 Jersey

php - 如何在执行另一个 SQL 查询 x 分钟后执行一个 SQL 查询?

java - 如何将此shoutOut Canned Message() 方法放入新类中?

c# - MongoDB 客户端在 mscorlib 中引发 FileNotFoundException

java - 使用 Hibernate Spring .getCurrentSession() 后出错

java - 如何自动比较两个 JSON 响应

java - 创建库以使用 JOGL 绘制 3D 对象