1

I have an application that does:

void deleteObj(id){
    MyObj obj = getObjById(id);
    if (obj == null) {
        throw new CustomException("doesn't exists");
    }
    em.remove(obj);//em is a javax.persistence.EntityManager
}

I haven't explicitly configure optimistic locking with version field.However, if two request are running in parallel, trying to delete the same object, then I get sometimes an HibernateOptimisticLockingFailureException and other times the "CustomException".

Is it normal to get HibernateOptimisticLockingFailureException without explicitly setting optimistic locking ? Does hibernate a default optimistic locking for detached objects ?

What are you doing to handle this HibernateOptimisticLockingFailureException ? Retry or inform to the user with a default message like "server busy" ?

1 Answer 1

4

First of all, HibernateOptimisticLockingFailureException is a result of Spring's persistence exception translation mechanism. It's thrown in response to StaleStateException, whose javadoc says:

Thrown when a version number or timestamp check failed, indicating that the Session contained stale data (when using long transactions with versioning). Also occurs if we try delete or update a row that does not exist.

From the common sense, optimistic lock exception occurs when data modification statement returns unexpected number of affected rows. It may be caused by mismatch of version value as well as by absence of the row at all.

To make sure that entity was actually removed you can try to flush the context by em.flush() right after removing and catch an exception thrown by it (note that it should be subclass of PersistenceException having StaleStateException as a cause).

Sign up to request clarification or add additional context in comments.

4 Comments

tks! "Also occurs if we try delete or update a row that does not exist", it seems that this is my case. What is a good way to handle the exception ? retry ? or shall I send a default message like "server busy" ?
You know, retrying is unlikely to make the row appear again. And a busy server should not make rows disappear from your database, should it?
As for how to handle it, simply ignore the exception? Delete should cause the row to no longer exist - if that's already the case before issueing a delete you're already done.
@meriton: You can react to optimistic lock exception by showing something like "Can't execute operation because data to be changed no longer exist"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.