Kivan
Kivan

Reputation: 1742

Is there a generic way to work with optimistic locking using Hibernate/Spring Data JPA?

I'm using hibernate's @Version annotation for optimistic locking. My usual use case for updating something in DB looks like this:

  1. Open a transaction (using @Transactional)
  2. Select entities I need to change
  3. Check if I can make the needed changes (validation step)
  4. Do changes
  5. Save everything (Spring Data JPA repository save() method), commit transaction
  6. If I catch any of OptimisticLockException, then I have to retry everything from step 1 (until successful save or fail on validation step, and not more than X times)

This algorithm looks quite common for any kind of optimistic locking processing. Is there a generic way using hibernate or spring data jpa to do these retries/handling of optimistic locking failures or should I write method like this myself? I mean something like (but not literally):

boolean trySaveUntilDoneOrNotOptimisticLockingExceptionOccur(Runnable codeWhichSelectsValidatesUpdatesAndSavesDataButWithoutOptimisticLockingProcessing, int maxOptimisticLockingRetries)

Upvotes: 1

Views: 333

Answers (1)

ram
ram

Reputation: 1169

As the question is tagged with spring-data-jpa, I will answer from Spring world.

Just have a look at @Retryable. I find it quite useful for exactly the same use case you describe. This is my usual pattern:

@Service
@Transactional
@Retryable(maxAttempts = 7, 
            backoff = @Backoff(delay = 50), 
            include = { TransientDataAccessException.class,
                        RecoverableDataAccessException.class }
)
public class MyService {

    // all methods in this service are now transactional and automatically retried.

}

You can play with backoff options, of course.

Check out here for further examples on @Retryable.

Upvotes: 3

Related Questions