In the context of REST APIs, databases, and Spring Boot, pessimistic locking and optimistic locking are two ways to manage data updates. This ensures data consistency but can cause delays.
Pessimistic Locking : Spring Boot allows the use of pessimistic locks through JPA’s @Lock annotation or by specifying lock options in a query.
How it works: When a record is read with a pessimistic lock, it is locked for others, preventing any other transaction from modifying it until the lock is released. This avoids conflicts but can reduce performance.
Example:
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT p FROM Product p WHERE p.id = :id") Product findProductForUpdate(@Param("id") Long id);
Optimistic locking doesn’t lock the record initially. Instead, it checks if the data has changed before updating. If another user has modified the data, the operation fails, and the user must retry. This method is faster and more efficient but requires careful error handling.
Versioning: Spring Boot uses a version field in the entity, typically annotated with @Version. Each time the entity is updated, the version number increases.
How it works: When an update is made, the version number in the database is checked. If it matches the version in the entity, the update proceeds. If another transaction has modified the entity (and thus changed the version), an OptimisticLockException is thrown, signaling a conflict.
Example:
@Entity
public class Product {
@Id
private Long id;
@Version private int version; // other fields, getters, and setters
}

Hinterlasse einen Kommentar