我遇到了 Hibernate 抛出的 NonUniqueObjectException
问题。
阅读文档和this博文中,我将 update()
的调用替换为 merge()
,问题就解决了。
我相信我理解异常的原因,以及为什么更改方法可以解决问题,就断开的对象和 session 边界而言。
我的问题是:鉴于 merge()
将始终解析为 session 对象,或者如果它不存在则检索它,调用 merge() 通常比 更安全更新()
?
使用 merge()
而不是 update()
有什么缺点?
最佳答案
Is calling merge() generally a safer alternative than update() ?
作为一种避免 NonUniqueObjectException 的方法,是的。我认为它解释了为什么 JPA 不允许更新方法。
What is the downside of using merge() over update() ?
未经建议的用户可能会认为他或她有一个新的托管实体。类似的东西
// myEntity (passed as parameter does not become managed)
// Only the one returned by the merge operation is a managed entity
session.merge(myEntity);
// "newValue" is not commited because myEntity is not managed
myEntity.setMyProperty("newValue");
如果您的持久性上下文不包含您的实体,也许您不希望 select-before-updating 默认行为。但可以避免
- 添加版本 (@Version) 列。 0 或 NULL 版本表示实例是新的,必须插入,而不是更新
- 使用 Hibernate 拦截器
- 如果您确定要更新而不是插入,可以使用以下方法
...
public void updateMyEntity(MyEntity updateableMyEntity);
// load does not hit the database
MyEntity myEntity = (MyEntity) session.load(MyEntity.class, updateableMyEntity.getId());
BeanUtils.copyProperties(myEntity, updateableMyEntity);
}
这样您就可以在没有合并或更新方法的情况下更新您的实体。有关更多信息,请参阅此问题:Best way to update some fields of a detached object on Hibernate ?
关于java - hibernate : Downside of merge() over update(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2118257/