[solved] org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:
Table of Contents
Meaning of this exception:
If we are trying to save the same identifier (primary key) with different session we will get this error.
How I solved ?
I have used Transaction and session previosly, then I replaced those things with getHibernateTemplate,
getHibernateTemplate().saveOrUpdate(myBean);
Then issue got resolved.
In another scenario,getHibernateTemplate().saveOrUpdate(myBean); for the same I got the same exception that is because I assigned null to myBean after save or update so if same identifier comes it producing the issue.
So I changed
getHibernateTemplate().saveOrUpdate(myBean);
myBean = null
to
getHibernateTemplate().saveOrUpdate(myBean);
//myBean = null
If the above ways did not work for you then try this too,
getHibernateTemplate().merge(myBean);
In case if you are facing the same error with spring data jpa:
Solution 1 with Spring Data JPA:
Make the exact save logic method in other words, where exactly your repository .save method is called that wrapper method you need to keep as public & with @Transactional annotation.
Solution 2 with Spring Data JPA:
@PersistenceContext private EntityManager entityManager;
and clear the session with .flush method just after your save()
entityManager.flush();
Please post your comments in comments area…..