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
我认为,在这两种情况下,这个标识符已经有了一个对象。同样......
答案 0 :(得分:1)
在本节中:
if the object's identifier has the value assigned to a newly instantiated object, save() it
“分配给新实例化对象的值”表示Java为实例变量提供的默认值。对于'String'变量,它将为'null',对于'int'变量,它将为'0'。
接下来我将举一个例子。它没有多大实际意义,但它证明了这一规则。
让我们从数据库中获取标识符为“0”的对象。此标识符的自动增加功能已启用。我们使用会话1获取DAO,然后关闭会话。
现在让我们初始化会话2并获得标识符为“0”的相同DAO。我们使用会话1将使用会话1检索的对象保存到数据库中。我们可以使用save或saveOrUpdate方法来保存对象。 DAO已使用新ID成功保存到数据库中。
当使用对象标识符'1'再现示例时,我们在保存对象时得到“NonUniqueObjectException”,并且数据库保持不变。
NonUniqueObjectException如下所述:
if another object associated with the session has the same identifier, throw an exception
我们已经证明实例变量是“相同标识符”规则的例外。