java 从休眠中的会话中删除对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3288838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
remove object from session in hibernate?
提问by Amr Faisal
Possible Duplicate:
Spring + Hibernate : a different object with the same identifier value was already associated with the session
I've loaded an object X from DB using hibernateTemplate find by id, then I get some attributes from that object and added it to another object Y from the same type which was also loaded by the same X id. Then when I tried to saveOrUpdateobject Y, hibernate throws exception a different object with the same identifier value was already associated with the session, which I think means that object X is associated with that attribute in the same session, so Y can't be saved or updated and affect also that attribute.
我已经使用 hibernateTemplate find by id 从 DB 加载了一个对象 X,然后我从该对象中获取了一些属性并将其添加到另一个相同类型的对象 Y 中,该对象也由相同的 X id 加载。然后,当我尝试saveOrUpdate对象 Y 时,hibernate 抛出异常,具有相同标识符值的不同对象已经与 session 关联,我认为这意味着对象 X 与同一会话中的该属性关联,因此无法保存 Y或更新并影响该属性。
How can I remove object X from session so it's no longer associated with that attribute
如何从会话中删除对象 X 使其不再与该属性相关联
I tried to use merge instead of saveOrUpdateand it's working fine, but is it the same as saveOrUpdate? I mean can I depend on it to add new records or update them?
我尝试使用 merge 而不是saveOrUpdate并且它工作正常,但是它与saveOrUpdate? 我的意思是我可以依靠它来添加新记录或更新它们吗?
回答by Amr Faisal
After a lot of tries, I found that using merge is the best approach to handle this effectively, and to take care of new instances to be saved I think best approach is to do this:
经过多次尝试,我发现使用合并是有效处理此问题的最佳方法,并且要处理要保存的新实例,我认为最好的方法是这样做:
if (X.getId() != null) {
return hibernateTemplate.merge(X);
} else {
hibernateTemplate.saveOrUpdate(X);
}
So if it was a new instance to session it'll be done through saveOrUpdate, and if it's a duplicated instance for the same rows, it'll be handled using merge.
因此,如果它是会话的新实例,它将通过 完成saveOrUpdate,如果它是相同行的重复实例,则将使用合并处理。
回答by Abhijeet Kashnia
Perhaps you can try session.evict().
也许你可以试试 session.evict()。

