Spring Boot & Microservices (50 Qs)•Part 2: Persistence, Transactions & Security (11 - 24)
How do Optimistic and Pessimistic Locking work in JPA?
mid LevelCode ExampleState ManagementSecurity & AuthDatabases & SQL
In Simple Words:
- Optimistic Locking: Assumes low conflict. Uses a
@Versionnumber column. When updating, SQL checksWHERE id = ? AND version = ?. If another transaction incremented the version, anOptimisticLockExceptionis thrown. No database locks held. - Pessimistic Locking: Assumes high conflict. Uses database row locks (
SELECT ... FOR UPDATEviaLockModeType.PESSIMISTIC_WRITE). Other transactions block until the lock is released.
java
@Entity
public class Account {
@Id private UUID id;
private BigDecimal balance;
@Version // Optimistic Lock
private Long version;
}
public interface AccountRepository extends JpaRepository<Account, UUID> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT a FROM Account a WHERE a.id = :id")
Optional<Account> findByIdForUpdate(@Param("id") UUID id);
}