'Spring JPA PESSIMISTIC_WRITE lock mode does not lock rows when other transactions read the same row
The following is a transaction method that retrieves an existing row from the database and updates one of its column value and then saves back to the database:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public A updateTotalItem(String id, int newItemNum) {
A a = aRepository.findById(id).orElseThrow(() -> new IllegalArgumentException());
a.updateValues(newItemNum);
return aRepository.save(a);
}
And I have applied a PESSIMISTIC_WRITE lock to aRepository.findById():
@Repository
public interface ARepository extends JpaRepository<A, String> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
Optional<A> findById(String id);
}
However, I discovered that if there are two concurrent calls to the above transaction method (with the same id argument provided), even though the first transaction will block the update of the second transaction, but after the first transaction committed, the second transaction would not retrieve the row with updated data, instead, it would still get the row with data prior to the first transaction committed. If I understand PESSIMISTIC_WRITE lock correctly, it should lock the row/entity for read/write, but in this case, looks like it only locks it for writing, am I understanding it wrong? If I am, is there any approach I can use to achieve the effect to lock the row/entity for read/write to prevent concurrent transactions getting the old data?
PS: I am using Hibernate as ORM and Postgres as database
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
