user1079475
user1079475

Reputation: 420

How to enforce write lock on table row using JPA/Spring/Hibernate

Is there an easy way to enforce somewhat concatenation of Isolation.REPEATABLE_READ and write locking for select statements, so once i've read a row in the transaction T1, all other transactions attempting to read that same row will hang untill T1 is commited/rolledback?

Upvotes: 0

Views: 2524

Answers (2)

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 18979

Use on your service method or wherever you want this annotation to open a transaction with the isolation level of Repeatable_Read that you want

@Transactional(isolation = Isolation.REPEATABLE_READ)

remember to import that annotation from org.springframework.transaction.annotation;

and not from javax.*

If you want to also lock concurent reads go to your JPA method that brings the entities to you, if you use one of the defaults, then define it again in your repo, and use the following annotation

@Lock(LockModeType.PESSIMISTIC_WRITE)
List<MyEntity> findByName(String name);

@Lock must be called inside a transaction otherwise it throws an exception. So the @Transactional before is mandatory

Check here for more information Lock Modes in JPA

Upvotes: 2

wi2ard
wi2ard

Reputation: 1545

It sounds like you need pessimistic locking using PESIMISTIC_WRITE strategy

Upvotes: 1

Related Questions