Junior — Middle
Have you used the Optimistic Locking mechanism in Spring development, and how is it implemented?
sobes.tech AI
Answer from AI
Optimistic Locking in Spring is usually implemented using the @Version annotation in JPA entities. It helps to avoid conflicts when multiple transactions update data simultaneously without explicitly locking records in the database.
Working principle: each time a record is updated, the version is incremented. If, upon saving, the version in the database does not match the object's version, it means the data has been modified by another process, and an OptimisticLockException is thrown.
Example:
@Entity
public class Product {
@Id
private Long id;
private String name;
@Version
private Integer version;
// getters and setters
}
When using a Spring Data JPA repository, if two transactions try to update the same object simultaneously, one will receive an exception, allowing for proper conflict handling.