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

项目中出现org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated withthe session这个错误。


自己的项目中出现这种现象:
是在更新某个操作对象时,前端传的是一个实体对象,该实体对象包含了主键id,后台根据这个主键去查询数据库中保存的原该对象信息,但最终保存的又是前端传过来的实体对象,导致在hibernate中同一个session里面有了两个相同标识但是是不同实体,导致调用getHibernateTemplate().saveOrUpdate(o);报错。还是由于自己的使用不当造成的。

解决方案:
1、更新时,如果需要根据主键id去查询原来的数据对象,那么将查询出来的结果作为最终的保存对象即可。
2、网上说的是使用getHibernateTemplate().getSessionFactory().getCurrentSession().evict(Object o);经测试也行,如果保存的是更新的对象,则把查询出的对象先清除


猜你喜欢

转载自xu-nuo.iteye.com/blog/2358299