Sobes.tech
Junior — Middle

How to implement data locking mechanisms when working with Spring Data?

sobes.tech AI

Answer from AI

Spring Data uses optimistic and pessimistic locking mechanisms to implement data locking.

  • Optimistic Locking is based on the record version. A field, for example @Version, is added to the entity, which automatically increments upon update. If the version has changed during save, an exception is thrown.
@Entity
public class Product {
    @Id
    private Long id;

    @Version
    private Integer version;

    // other fields
}
  • Pessimistic Locking locks the record in the database for the duration of a transaction. In Spring Data, you can use the @Lock annotation with PESSIMISTIC_READ or PESSIMISTIC_WRITE lock modes in the repository:
public interface ProductRepository extends JpaRepository<Product, Long> {
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select p from Product p where p.id = :id")
    Optional<Product> findByIdForUpdate(@Param("id") Long id);
}

Thus, the choice of mechanism depends on the requirements for concurrency and performance.