org.hibernate.NonUniqueObjectException: a different object with the same identifier value was alread

问题

使用hibernate更新对象时,出现如下错误:
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:
[com.csdn.constantConfiguration.entity.Constantconfiguration#402881456f12c32a016f131ad044001f]

原因

在session中不同对象有相同的唯一标识(NonUniqueObjectException)
在同一个session内,如果已经有一个对象已经是持久化状态(数据库中已存在),现在构造一个新的对象,和前一个持久化对象拥有相同的持久化标识(identifier),在update的时候,就会报错。
举个例子(伪代码):

Object o1=objectService.getId("123");//根据id从数据库中查询出结果
Object o2=new Object();
o2.setId("123");
o2.setVelue(o1.getValue);
objectService.saveOrUpdateObject(o2);//此处报错

解决方法

1.使用hibernate的merge方法更新对象

sessionFactory.getCurrentSession().merge(object);

2.先清除session,再update

sessionFactory.getCurrentSession().clear();
objectService.saveOrUpdateObject(o2);
发布了19 篇原创文章 · 获赞 2 · 访问量 721

猜你喜欢

转载自blog.csdn.net/qq_40977118/article/details/104371551