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

problem

When updating objects using hibernate, the following error appears:
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:
[com.csdn.constantConfiguration.entity.Constantconfiguration # 402881456f12c32a016f131ad044001f]

the reason

Different objects in the session have the same unique identifier (NonUniqueObjectException)
in the same session. If an object is already in a persistent state (already exists in the database), now construct a new object, which is owned by the previous persistent object The same persistent identifier (identifier), when updating, will report an error.
For example (pseudo code):

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

Solution

1. Use hibernate's merge method to update the object

sessionFactory.getCurrentSession().merge(object);

2. Clear the session first, then update

sessionFactory.getCurrentSession().clear();
objectService.saveOrUpdateObject(o2);
Published 19 original articles · Likes2 · Visits 721

Guess you like

Origin blog.csdn.net/qq_40977118/article/details/104371551