Hibernate_Error_a different object with the same identifier value in session

Hibernate_Error:

a different object with the same identifier value was already associated with the session

 

又碰到这个问题,编程的时候早忘记了,自己先前已经把一个相同Id的entity加载进了内存。

 

导致错误的过程分析:

1) 自己先前因为某种原因已经把一个entity跟session关联上了

      关联的方式和内容有:

    A. 直接根据Id把entity加载进内存留待使用

    B. Update一个entity,但是update之后,此entity仍旧在内存中,留待使用

2) 又来了一个新的entity,Id和先前的相同,内容不同

3) session.update(entity) 报错了(注意update的同时也要把此entity和session关联)

    原因:session不知道该去持久化哪个entity

 

弄清楚了原因,解决方法其实可以千变万化,不必拘泥于网上Google来的各种解决方法。

 

另外需要很好的理解Hibernate中的对象类型,以及其转化条件和关系。

 

另外,有的网友说用Hibernate的session.merge()方法不好,好像用框架自己的方法就是不好一样。其实不是不好,而是需要理解merge究竟做了些什么。

Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped with cascade="merge" .

看,merge帮我们做了这么多事情。[哈哈,的确不好]

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值