Hibernate – @Version Annotation with Example
Last Updated :
07 Jun, 2023
@Version annotation is used to specify the version number for a specific entity. Version Number provided using @Version annotation is used to prevent concurrent modification to an entity. When an entity is being updated, the version number is also incremented. If another transaction tries to update the same entity with the older version number, an exception will be given. The version number helps to prevent conflicts between concurrent transactions. @Version annotation is used for optimistic locking. Optimistic locking is a concurrency control mechanism in which it ensures that concurrent transactions will not conflict with each other. If there is a chance of conflict during transactions the transaction having an older version number will be aborted.
Examples of @Version Annotation
Example 1:
Java
package com.example.java_test_application;
@Entity
public class Employee {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Long empId;
private String employeeName;
private String employeeQualification;
@Version
private int version;
}
|
Explanation: In the above example, we are considering an Employee entity with a version field annotated with @Version. The version field will be used for optimistic locking. Whenever this entity field is being updated sequentially the value of the version is also checked to ensure that it matches the current version in the database. If the version has changed, an exception will be thrown, indicating a concurrent modification.
Example 2:
Java
@Entity
public class Department {
@Id
@GeneratedValue (strategy = GenerationType.SEQUENCE)
private Long departmentID;
private String departmentName;
@Version
private Long version;
}
|
Explanation: In the above example, we are considering a Department entity in which we are creating a version field annotated with @Version. This version field is used for optimistic locking. When the Department entity is being updated it will first check the version to ensure that it will match the current version in the database. If the version has changed an exception will be thrown indicating a concurrent modification.
Share your thoughts in the comments
Please Login to comment...