java - hibernate saveOrUpdate() 这两种情况有什么区别

标签 java 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

本条款:

"if another object associated with the session has the same identifier, throw an exception"

这样:

•if the object's identifier has the value assigned to a newly instantiated object, save() it

我认为,在这两种情况下,已经有一个对象这个这个标识符。一样的...

最佳答案

在本条款中:

if the object's identifier has the value assigned to a newly instantiated object, save() it

“分配给新实例化对象的值”是指Java赋予实例变量的默认值。对于“String”变量,它将是“null”,对于“int”变量,它将是“0”。

<小时/>

接下来我将举一个例子。虽然没有多大实际意义,但它证明了这个规则。

让我们从数据库中获取一个标识符为“0”的对象。该标识符的自动增加功能已开启。我们使用 session 1 获取 DAO,然后关闭 session 。

现在让我们初始化 session 2 并获取标识符为“0”的相同 DAO。我们将使用 session 1 检索到的对象保存到 session 2 的数据库中。我们可以使用 save 或 saveOrUpdate 方法来保存对象。 DAO 已使用新 ID 成功保存到数据库中。

当重现对象标识符“1”的示例时,我们在保存对象时收到“NonUniqueObjectException”,并且数据库保持不变。

NonUniqueObjectException 的给出如下:

if another object associated with the session has the same identifier, throw an exception

我们已经证明实例变量是“相同标识符”规则的异常(exception)。

关于java - hibernate saveOrUpdate() 这两种情况有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22739812/

相关文章:

java - Hibernate延迟加载不起作用,强制需要急切加载

java - 如何将 Map<String,String> 更改为 Map<String,Ratio> ,比率为 x/y

java - 处理多个 HTTP 连接

java - Apache Ignite Hibernate L2 缓存与 Spring Boot

java - 列出电话号码的所有国家代码

java - 对机器人进行编程以探索网格

java - 如何将 Hibernate 验证注释与枚举一起使用?

hibernate - OpenEJB 与 Tomcat、Hibernate 和 JPA

java - HTTP 状态 500 - 未能延迟初始化角色 : . 的集合 ..,无法初始化代理 - 无 session

spring - 错误:org.hibernate.hql.internal.ast.QuerySyntaxException,请帮助我?