inor
inor

Reputation: 2846

Is there a way to avoid HibernateOptimisticLockingFailureException?

i have a persistent hibernate managed @entity Obj in Hibernate, which has fields id, fieldA, and fieldB, among others.

In some class i have two @Transactional methods, updateA() and updateB().
updateA() obtains an Obj by its id, does some processing, and updates its fieldA.
updateB does same for fieldB.

I also have two clients that continuously make requests. One client always makes requests that call updateA(), and the other client always calls updateB().
They both pass the same id of an existing Obj.

Is there a way to avoid the HibernateOptimisticLockingFailureException that keeps occurring, or to handle it once successfully, given the fact that each method updates different fields? Some kind of a merge?

Just to complete the picture, the thread that calls updateA() in fact calls other transactional methods similar to updateA(), but none updates fieldB.

At first I just tried to catch the exception and re-try the operation a second time. But sometimes it fails the second time too... This does not seem like a good solution.

Upvotes: 1

Views: 2560

Answers (2)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153690

You can use an automatic optimistic locking retry mechanism.

For that you need to add the following dependency:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>db-util</artifactId>
    <version>0.0.1</version>
</dependency>

Then just mark your service methods with the following annotation:

@Retry(times = 5, on = OptimisticLockException.class)

Upvotes: 2

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

If you can safely do it, the easiest way is to exclude fieldB from optimistic locking:

import org.hibernate.annotations.OptimisticLock;

/* ... */

@OptimisticLock(excluded=true)
private B fieldB;

Upvotes: 2

Related Questions