Hibernate中遇到的一个Exception

做项目的时候遇到一个很头疼的报错:Illegal attempt to associate a collection with two opensessions 

出错原因:  一个Object Version 包含了两个oneTomany关系。在数据库调取出一个version对象时,再用saveOrUpdate这个对象就会出现如上错误

解决办法:  讲session.saveOrUpdate(version)改为session.merge(version)

原理分析:  saveOrUpdate是在同一个session里用于保存或更新一个条目,而merge可以用于两个不同session数据的保存或更新。
HibernateReference里说:

saveOrUpdate() does the following:

  • if the object is already persistent in this session, donothing
  • if another object associated with the session has the sameidentifier, throw an exception
  • if the object has no identifier property, save() it
  • if the object's identifier has the value assigned to a newlyinstantiated object, save() it
  • if the object is versioned by a or , and the version property valueis the same value assigned to a newly instantiated object, save()it
  • otherwise update() the object

merge() is very different:

  • if there is a persistent instance with the same identifiercurrently associated with the session, copy the state of the givenobject onto the persistent instance
  • if there is no persistent instance currently associated with thesession, try to load it from the database, or create a newpersistent instance
  • the persistent instance is returned
  • the given instance does not become associated with the session, itremains detached

网上有其他资料说代码如下:entity=merge(entity);  saveOrUpdate(entity);这是错误的,第二行代码完全没有必要,因为entity已经是persistentobject,会被saveOrUpdate忽略。直接用session.merge(version)即可。

转载于:https://www.cnblogs.com/codingforum/p/4316865.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值