错误中学习--a different object with the same identifier value was already associated with the session

出现如下错误

a different object with the same identifier value was already associated with the session的场景是:


我直接用hql的update(obj)更新一条数据,但是有两个字段因为没有值被更新成了null,所以想在更新前,先把这两个字段查出来赋值给实体类,这样更新的时候可以用到原来的值

我在service层中先发出一条select语句,但是报如上的错,翻译一下就是说在hibernate中同一个session里面有了两个相同标识但是是不同实体.

网上有很多解决办法,我后来在action层查询出来赋值给实体类就可以了.


但是,看到一个新的方法merge(),测试了一下

merge()会先发出一条selectById语句进行查询,返回值是Object,

如果记录不存在,会执行insert语句,

如果记录存在,会执行updata语句

我在接到编辑界面的数据后重新给id赋了一个数据库不存在的值,最终新insert后的数据是把接收到的数据复制过去的,


错误中学习--a different object with the same identifier value was already associated with the session


还有别的解决办法参照下面的链接

点击打开链接

错误中学习--a different object with the same identifier value was already associated with the session