How to retry JPA transactions after an OptimisticLockException

This is the third part of the optimistic locking series, and I will discuss how we can implement the automatic retry mechanism when dealing with JPA repositories. You can find the introductory part here and the MongoDB implementation here.

JPA requires running the Persistence Context code inside a Transaction, and if our Transaction Manager catches a RuntimeException, it initiates the rollback process. This makes the Persistence Context unusable since we should discard it along with the roll-backed Transaction.

Therefore it’s safer to retry the business logic operation when we are not within a running Transaction.

If we are running inside a Transaction and we don’t suppress the default safe-check we then throw an IllegalTransactionStateException, notifying the caller that’s safer to retry if the Transaction is contained in the proceeding service call, without nesting our intercepting aspect.

This utility is part of my db-util project along with the MongoDB optimistic concurrency control retry mechanism.

Since it’s already available in Maven Central Repository, you can easily use it by just adding this dependency to your pom.xml: