简体   繁体   中英

Saving/updating object with hibernate

My class Foo has method:

 protected void saveMany(Collection<T> many) {  
    for(Object one : many) {
            one = session.merge(one); // also tried this commented out
            session.saveOrUpdate(one); // session.merge(one);   
        }

Tried to use saveOrUpdate and also merge, but both gave me this exception:

Error: Invocation of method 'saveMany' in class Foo threw exception class org.hibernate.HibernateException : org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [Bar#581301]

How to fix this?

Side note:

When I truncate my table, the saving part works, but when I have the table populated, and run this method again, thus updating the table, it fails, with this exception

If you have a detached instance of a Class with @Id that already exists in the Hibernate Session cache, then you will have to call merge() to merge the detached instance into the cache. Then you should call saveOrUpdate() .

But you have to be careful to persist the instance returned from the call to merge() and not the instance you passed in as a parameter. So you code has to look like this

mergedOne = session.merge(one);
session.saveOrUpdate(mergedOne);

If you're operating inside a transaction the database will not be updated until the session ends and the transaction commits, or you explicitly call flush()

It says that you are trying to save a new object with an Id already used by another one.

Probably, you do not have properly implemented equals and hashCode . So, hibernate finds that you want to save Object2 with id1, and in the database there is Object2 with id1, but not Object2.equals(Object1)

You have multiple versions of "one" in the cache of your Hibernatesessions!

You must must find the instances of "one" and remove the cache-information from the Hibernatesessions using ".evict(...)".

Finally you can call saveOrUpdate succesuflly!

You are probably trying to Save List<T> which has one or more equals objects.

Use SaveOrUpdate or merge to solve it or simpply try to make all objects unique.

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