How to solve org.hibernate.NonUniqueObjectException: another object with the same identifier value was already associated with the session:

I save Listusing sleep mode, but it throws the following exception:

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:

The code I'm using is below, but I don't know why it throws an exception:

public void save(List<UserItem> list)
{
    //getHibernateTemplate().saveOrUpdateAll(list);

    //getHibernateTemplate().deleteAll(list);
    sessFactory = getHibernateTemplate().getSessionFactory();
    Session session = sessFactory.getCurrentSession();
    for (UserItem bean : list) {
        session.saveOrUpdate(bean);
    }
}

What is the correct way to save List?

+4
source share
2 answers

The problem is that an object with this identifier already exists in the session, using merge will fix all your problems, but you should really look into the differences. Just copy this and it will work.

public void save(List<UserItem> list)
{
    //getHibernateTemplate().saveOrUpdateAll(list);

    //getHibernateTemplate().deleteAll(list);
    sessFactory = getHibernateTemplate().getSessionFactory();
    Session session = sessFactory.getCurrentSession();
    for (UserItem bean : list) {
        session.merge(bean);
    }
}

Hibernate?

+1

: , , .

, - . for session.saveOrUpdate(bean);.

0

Source: https://habr.com/ru/post/1657131/


All Articles