Hibernate:merge() 比 update() 的缺点 [英] Hibernate : Downside of merge() over update()
问题描述
我遇到了 Hibernate 抛出的 NonUniqueObjectException
问题.
I'm having problems with a NonUniqueObjectException
thrown by Hibernate.
阅读文档,以及这个 博客文章,我将调用从 update()
替换为 merge()
,它解决了问题.
Reading the docs, and this blog post, I replaced the call from update()
to merge()
, and it solved the problem.
我相信我了解异常的原因,以及为什么更改方法可以解决断开连接的对象和会话边界方面的问题.
I believe I understand the reason for the exception, and why changing the method fixed the problem, in terms of disconnected objects and session boundaries.
我的问题是:鉴于 merge()
将始终解析会话对象,或者在它不存在时检索它,调用 merge() 通常比 更安全的替代方法update()
?
My question is : given that merge()
will always resolve to the session object, or retrieve it if it doesn't exist, is calling merge() generally a safer alternative than update()
?
使用 merge()
而不是 update()
的缺点是什么?
What is the downside of using merge()
over update()
?
推荐答案
调用 merge() 通常比 update() 更安全吗?
Is calling merge() generally a safer alternative than update() ?
作为一种避免 NonUniqueObjectException 的方法,是的.我想这解释了为什么 JPA 不允许更新方法.
As a way to avoid NonUniqueObjectException, yes. I think it explains why JPA does not allow an update method.
使用 merge() 而不是 update() 的缺点是什么?
What is the downside of using merge() over update() ?
不知情的用户可能认为他或她有一个新的托管实体.类似的东西
An unadvised user may think he or she has a fresh managed entity. Something like
// 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");
如果您的持久化上下文不包含您的实体,也许您不希望更新前选择默认行为.但是可以避免
And if your persistence context does not contain your entity, maybe you do not want select-before-updating default behavior. But it can be avoided
- 添加版本 (@Version) 列.0 或 NULL 版本表示实例是新的并且必须插入,而不是更新
- 使用 Hibernate 拦截器
- 如果您确定要更新而不是插入,可以使用以下方法
- Add a version (@Version) column. 0 or NULL version indicates that an instance is new and has to be inserted, not updated
- Use a Hibernate interceptor
- If you are sure you want to update instead of inserting, you can use the following approach
...
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如何在 Hibernate 上更新分离对象的某些字段?
This way you can update your entity without merge or update method. See this question for more information: Best way to update some fields of a detached object on Hibernate ?
这篇关于Hibernate:merge() 比 update() 的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!