0

So here is how it goes,

After reading about locking transactions in Spring JPA for ACID properties, I did a POC(proof of concept) to get working with transactions.

In my scenerio, I have two applications trying to access the database with read and write operations. Both applications have controller, entity and repository for a sample table with 3 columns.

In my first application, controller goes like:

@GetMapping("/test")
@Transaction
JpaPOC jpaPoc = jpaRepository.findById(2);

// Some system out prints

// Sleep thread for 2 minutes

// set or change one or more properties

jpaRepository.save(jpaPoc);

Repository File:

@Lock(LockModeType.PESSIMISTIC_WRITE)
Optional<JpaPoc> findById(Integer id);

In my second application theres a controller, blank repository and same entity.

Controller

@GetMapping("/test")
@Transaction
JpaPOC jpaPoc = jpaRepository.findById(2);

//some system out prints for testing
// setting the jpaPoc property to something else

jpaRepository.save(jpaPoc);

//Success print

Now the thing is that When I run this applications and hit controller methods (first and the second) my second controller is not waiting for the lock to be released.. Its working just like that and updating the values.

Furthermore, lets say that we did end up fixing things and its waiting now for the lock to be released.

Now lets say I don't want the second transaction to wait for the lock to be released then perform the operation. I want it to throw a exception that its locked and rollback itself. Is there any advice that I can take on this.. It would be of great help

Thanks in Advance..

Aayush
  • 409
  • 4
  • 17
  • Does it work when you rename the custom `findById` to something else (e.g. `findLockedById`)? My guess would be `@Lock` is only picked up for custom repository methods. Also, are you sure transactions are configured properly? What does `TransactionSynchronizationManager.isActualTransactionActive()` return inside the methods? – crizzis Mar 18 '21 at 15:42
  • Regarding the second question, [this](https://stackoverflow.com/questions/29765934/how-to-specify-lock-timeout-in-spring-data-jpa-query) might be helpful – crizzis Mar 18 '21 at 15:44
  • Hi @crizzis, thanks for the help. I changed the methods to LockById and I added ```@QueryHints({@QueryHint(name = "javax.persistence.lock.timeout", value ="0")})``` in the first repository method... But still it is not throwing a locktimeout exception in the second one... Am I missing something here ? And yes ```TransactionSynchronizationManager.isActualTransactionActive()``` is returning true for both of them ? – Aayush Mar 20 '21 at 16:23

0 Answers0