Meenal
Meenal

Reputation: 153

org.springframework.orm.ObjectOptimisticLockingFailureException

While trying to insert into database, I'm getting below stack trace:

org.springframework.orm.ObjectOptimisticLockingFailureException: 
Batch update returned unexpected row count from update [0]; 
actual row count: 0; expected: 1; 
nested exception is org.hibernate.StaleStateException: 
Batch update returned unexpected row count from update [0]; actual row count: 0

Any idea, why do we get this exception and the resolution. This issue is occuring intermittently and I am not observing it every time I hit my service.

Upvotes: 2

Views: 3671

Answers (1)

htshame
htshame

Reputation: 7330

The idea behind ObjectOptimisticLockingFailureException is the following:

Let's say you have a multi-threaded process that is supposed to delete number of records in your database.

Each thread executes the same code, e.g.:

Foo foo = repository.findById(id);
reposiroty.delete(foo);

Let's say that thread A found Foo entity by id = 1, and before thread A have gotten to reposiroty.delete(foo);, thread B also acquired Foo entity with id = 1.

So after Foo with id = 1 is deleted by thread A, thread B will try to do the same thing, but since Foo with id = 1 is already will be deleted at that time, thread B will throw ObjectOptimisticLockingFailureException.

Hence, thread B was hoping to delete the acquired entity, but this entity was already deleted by the time thread B actually started to perform the deletion.

As an option, you may catch ObjectOptimisticLockingFailureException and implement some logic based on this scenario.

Upvotes: 1

Related Questions