Skip to main content
InterviewHubPRO
Section Overview
Q20

Question 20 of 50

Part 2: Persistence, Transactions & Security (11 - 24)

40%
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 @Version number column. When updating, SQL checks WHERE id = ? AND version = ?. If another transaction incremented the version, an OptimisticLockException is thrown. No database locks held.
  • Pessimistic Locking: Assumes high conflict. Uses database row locks (SELECT ... FOR UPDATE via LockModeType.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);
}