我有一个用户类
class User {
int id;
String name;
}
id
是 User.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/