从休眠中的会话中删除对象? [英] remove object from session in hibernate?

查看:117
本文介绍了从休眠中的会话中删除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

不同的对象具有相同的标识符值, / blockquote>



我使用hibernateTemplate find by id从数据库加载了一个对象X,然后从该对象中获取一些属性并将其添加到另一个来自同一类型的对象Y,它也由同一个X id加载。然后,当我试图使用 saveOrUpdate 对象Y时,hibernate抛出异常具有相同标识符值的不同对象已与会话相关联,我认为意味着对象X在同一会话中与该属性相关联,所以Y不能被保存或更新并且也影响该属性。



如何删除对象X来自会话,所以它不再与该属性相关联



我尝试使用merge而不是 saveOrUpdate ,它工作正常,但它是否与 saveOrUpdate 相同?我的意思是我可以依靠它来添加新记录或更新它们吗?

解决方案

经过大量尝试,我发现使用合并是有效处理这种情况的最佳方法,并且保存新实例以保存我认为最好的方法是执行此操作:

 <$ c (X.getId()!= null){
return hibernateTemplate.merge(X);
} else {
hibernateTemplate.saveOrUpdate(X);





$ b

因此,如果它是一个新的会话实例,它将通过 saveOrUpdate ,并且如果它是同一行的重复实例,它将使用合并处理。


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 saveOrUpdate object 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.

How can I remove object X from session so it's no longer associated with that attribute

I tried to use merge instead of saveOrUpdate and 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?

解决方案

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.

这篇关于从休眠中的会话中删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆