@Version is a JPA annotation used to handle concurrency by maintaining a version field in an entity. It helps track updates and ensures that multiple transactions do not overwrite each other’s changes. This mechanism is part of optimistic locking.
- Automatically increments the version value on each update
- Detects concurrent updates and prevents data conflicts
- Throws an exception if an outdated version tries to update the entity
Examples of @Version Annotation in JPA
Below examples demonstrate how @Version is used in entity classes to implement optimistic locking and handle concurrent updates safely.
Example 1:
package com.example.java_test_application;
// on the below line creating an entity
@Entity
public class Employee {
// generated value with the strategy for generation
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long empId;
private String employeeName;
private String employeeQualification;
// using version annotation.
@Version
private int version;
}
Explanation: This defines an Employee entity with a version field used for optimistic locking. Each update increases the version, and if a mismatch occurs during concurrent updates, an exception is thrown.
Example 2:
@Entity
public class Department {
// on the below line creating a
// variable for department id.
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long departmentID;
// on the below line creating a
// variable for department name.
private String departmentName;
// on the below line creating
// a variable for version.
@Version
private Long version;
}
Explanation: This defines a Department entity where the version field ensures safe updates. It checks the current version before updating and prevents conflicts if the data was modified by another transaction.