Sobes.tech
Junior — Middle

Can you explain the purpose of the @Version annotation in the context of concurrency control?

sobes.tech AI

Answer from AI

The @Version annotation is used in JPA (Java Persistence API) to implement optimistic locking when working with a database.

Its main purpose is to prevent data loss during concurrent access to the same record. When updating an entity, JPA checks the value of the field annotated with @Version. If the version in the database does not match the version in the object, it means that someone else has modified the record, and the update operation will be interrupted with an OptimisticLockException.

Example:

@Entity
public class Product {
    @Id
    private Long id;

    @Version
    private Integer version;

    private String name;
    private Double price;

    // getters and setters
}

Thus, @Version helps ensure data integrity without using database-level locks, which improves application performance and scalability.