gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:12:35 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com