您的位置:首页 > 移动开发 > Objective-C

org.hibernate.NonUniqueObjectException: a different object with the same ide

2014-11-12 11:30 399 查看
a different object with the same identifiervalue was already associated withthesession 问题的解决:

其实我没有特别好的解决办法,问题本身也是见仁见智的,需要针对不同场景不同业务逻辑随机应变.本文只是探讨性的文章,属于开放性质的.

从我的经验来说,我倾向于从两方面解决:

1.session方面

从程序的角度,多分析问题,找到session的开始和结束点.

不过说句实话,这真的很难,因为现在的代码越来越框架化,模块化,封装得越来越深,session根本不暴露在业务层之外,操作经常要上溯到很高层的父类,尤其当和事务挂钩时,更是复杂.而且现在session的底层操作也越来越晦涩,基于池操作的,基于ThreadLocal操作的,基于JTA的.

2.从update()方面

目前比较普遍的观点,用merge()方法解决是一个比较"傻瓜"的解决办法.

JSR-220里对session.merge()方法的描述:

Copy the state of the given objectonto the persistent object with the sameidentifier.

将给定对象的state(状态,即实例属性)拷贝给到具有相同id的持久化对象

If there is no persistent instance currently associated with thesession, it will be loaded. Return the persistent instance.

如果当前没有持久化对象关联到session,当前对象会被加载为持久化对象,并(在update后)返回持久化对象

If the given instance is unsaved, save a copy of and return it as anewly persistent instance. The given instance does not becomeassociated with the session.

如果给定实例还没存盘,就存一份copy,并且(这份)copy返回作为新的持久化对象.而给定的对象不会再关联到session

简单总结:

merge()会用"拷贝状态copy thestate",也就是属性赋值的直接方法,完成相同id对象的更新,实际就是把内容克隆过去.

如果是一个新的对象实例,merge()实际就等同于save()和persist()

但与save()和persist()不同,merge()完成后,其操作的对象是托管态.

转载于:http://blog.sina.com.cn/s/blog_6151984a0100kgsz.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐