在Hibernate中使用saveOrUpdate()创建新记录,而不是更新现有记录 [英] Using saveOrUpdate() in Hibernate creates new records instead of updating existing ones
问题描述
我有一个类User
class User {
int id;
String name;
}
其中 id
在 User.hbm.xml
和 name
中的原生生成器是数据库中的主键。
where id
is native generator in User.hbm.xml
and name
is primary-key in DB.
在我的数据库中,我保存了一些关于用户的信息。
In my database I saved some information about Users.
比我想要连接有关用户的这个信息。
Than I want to connect with this information about User.
例如在我的DB中,我有一行 INSERT INTO User VALUES('Bill');
For example in my DB I have a row INSERT INTO User VALUES ('Bill');
Main.java
Main.java
User bill = new User();
bill.setName("Bill");
session.saveOrUpdate(bill);
此代码总是尝试插入新的 Bill
row into the table,而不是更新现有的 Bill
行。
This code always tries to insert a new Bill
row into the table rather than update the existing Bill
row.
推荐答案
这段代码总是尝试向数据库插入帐单,而不是更新当DB在... ...
This code always trying insert bill to database , rather than update when row about Bill exists in DB...
从 10.7部分。自动状态检测 Hibernate核心文档:
From the section 10.7. Automatic state detection of the Hibernate core documentation:
saveOrUpdate()
执行以下操作:
- 如果对象在此会话中已持久化
,则不执行任何操作 - 如果与
会话相关联的另一个对象具有相同的标识符,则抛出
例外 - 标识符属性,
save()
it - 如果对象的标识符的值为
,实例化的
对象,save()
it - 如果对象是
版本化的< version>
或
< timestamp>
,版本
的属性值是相同的值
分配给新实例化的
对象,save()
it - 否则
update()
对象
- 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()
它,如文件。如果这不是你想要的,请使名称
为主键。
This newly created instance does not have any identifier value assigned and saveOrUpdate()
will save()
it, as documented. If this is not what you want, make the name
the primary key.
这篇关于在Hibernate中使用saveOrUpdate()创建新记录,而不是更新现有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!