简体   繁体   中英

Hibernate giving org.hibernate.NonUniqueObjectException and saving obsolete object to the database

I have below code in my service class. This code is called twice from 2 different methods as part of a functionality.

        //Some code here... 
        LOG.info("###Inside customer interceptor");
        try
        {
            customerDao.save(customer);

        }
        catch (final Exception exp)
        {
        //some code here too...
        }

When it is first time called from first method and executed, I can see that there is a select SQL statement printed in tomcat console, but there is no update SQL statement as I expected(May be because of the fact that Hibernate doesn't issue an insert/update immediately). Immediately When this code block is called again from second method, I see a SQL select statement and then a SQL update statement in tomcat console, and immediately after that I see a big fat org.hibernate.NonUniqueObjectException. which as I can understand coming because the earlier entity was still attached to session and not committed to DB.

However when I go and see the database I find the values saved in the database were of the object from first call and not the second one as I expected. Is this normal or am I missing something here?

I am using Spring's annotation(@Transactional) driven transaction strategy.

I'd rather use .merge(customer) method or .saveOrUpdate(customer) method to perform this operation.

  • If you use .merge , you will not get the nonUnique exception as it overwrites the object that is in the session with the one you just passed.
  • Where as to perform saveOrUpdate , the session should not have the same instance of the object you are trying to update or else you get this nonUniqueObject exception.

Because you are using spring @Transactional, the transaction should be committed after the complete method has been executed.

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