Sobes.tech
Junior — Middle

What is the purpose of the @Version annotation in JPA and how does it affect data concurrency control?

sobes.tech AI

Answer from AI

The @Version annotation in JPA is used to implement optimistic locking. It marks an entity field that stores the record's version (usually an integer or timestamp). When updating a record, JPA checks that the version in the database matches the version in the object to ensure that the data has not been modified by another transaction.

If the versions do not match, an OptimisticLockException is thrown, preventing overwriting data changed concurrently. This helps manage concurrent access without using database-level locks.

Example:

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

    @Version
    private Integer version;

    private String name;
    // getters and setters
}

Here, the version field is automatically updated with each change to the entity, providing version control.

What is the purpose of the @Version annotation in JPA… - sobes.tech