Retry entity save after ConstraintViolationException

My scenario is to re-try saving entity with new unique name if entity with same name already exists.
I have following code:

try {
            this.getSession().save(asset);
           //flush to immediately get an error if any
            this.getSession().flush();

           //caused by ConstraintViolationException on unique name
        } catch (PersistenceException e) {
            this.getSession().getTransaction().rollback();
            asset.rename(newName)
            saveAgain(asset);
        }

then retry saving entity with new name, but due to generated ids of my entity I got

javax.persistence.OptimisticLockException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

Seems like hibernate can’t insert new entity if it has filled id fields.
If I clone my entity without filled ids everything is OK.
I also found similar post but there are no answers:
https://forum.hibernate.org/viewtopic.php?f=1&t=999924

So, the only real solution - is to make a copy?
Any ideas how to cope with the issue?

Once you get an exception, you should no longer reuse the Hibernate Session or EntityManager.

What you need to use is MERGE or UPSERT, depending on the underlying database in use.

Thanks, merge works fine for this case!

I’m glad I could help.