Monday, November 18, 2024
Google search engine
HomeLanguagesJavaHibernate – @Version Annotation with Example

Hibernate – @Version Annotation with Example

@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;
  
// on the below line creating an entity
// class for the class of Employee.
@Entity
public class Employee {
   // on the below line creating an employee id 
   // generated value with the strategy for generation type. 
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long empId;   
   private String employeeName;    
   private String employeeQualification;
    
   // on the below line we are 
   // using version annotation. 
   @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




// on the below line creating an 
// entity class for the class of Department.
@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: 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.

RELATED ARTICLES

Most Popular

Recent Comments