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

本文探讨了在使用Hibernate框架时遇到的“adifferentobjectwiththesameidentifiervalue”错误,并提出了两种解决方案:一种是直接修改原始对象并更新;另一种是使用merge方法。
a different object with the same identifier value was already associated with the session

出现这种错误的根本原因是query得到一个对象A,然后update时又新建了一个对象B,虽然新建对象B的主键值取的对象A的值,但他们仍然是两个对象,这样update时就会报错。

解决办法:
一、不用创建对象B,要修改记录时,直接reset对象A的属性,然后update对象A

二、用merge不用update
Test obj = new Test();
...
getSession().flush();
getSession().clear();
//不要用update()方法
getHibernateTemplate().merge(obj);


但建议用方法一比较好
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值