简体   繁体   中英

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

I'm saving a List by using hibernate, 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 the 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 the List ?

The problem is that an object with that id already exists in the session, using merge will fix all of your problems but you should really look into the differences. Just copy this and it'll 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);
    }
}

Here's a good source for more info on the hibernate persistence related methods What are the differences between the different saving methods in Hibernate?

The main reason or cause of this error is, in your list there are objects with the same primary key, it means two object with same primary key but they are not same object instance.

I would suggest you to iterate your list and print your primary key value and find out if is there any object which has same primary key value. Just put print function in your for loop to print your primary key value for each object before calling session.saveOrUpdate(bean); line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM