Reputation: 1742
I'm using hibernate's @Version annotation for optimistic locking. My usual use case for updating something in DB looks like this:
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
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