Once a record is inserted in the database, we can update it any number of times. The versioning feature of hibernate is useful when we want to know how many times a particular record has been modified. This feature is useful in sensitive applications in the finance domain, where we need to record each and every data movement.
When we use the versioning feature, hibernate inserts the initial version number as zero. Whenever a record is modified, the value of the version is increased by one.
To work with the versioning concept, we have to make a small change in the POJO. We have to create a field with the numeric type and declare this field with the @version
annotation so that hibernate will consider it to be the versioning column.
The following code shows the Java file changes for versioning:
Source file: Employee.java
@Entity @Table(name = "employee") public class Employee { @Id @GeneratedValue @Column(name = "id") private long id; @Column(name = "name") private String name; @Version private long version; //getters and setters }
Use the following table script if the hibernate.hbm2ddl.auto
configuration property is not set to create
:
Use the following script to create the employee
table:
CREATE TABLE `employee` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `version` bigint(20) NOT NULL, PRIMARY KEY (`id`) );
Here, we will insert a record and see the table data after a successful insertion. Update the following code:
Session session = sessionFactory.openSession(); Transaction transaction = session.getTransaction(); transaction.begin(); Employee employee = new Employee(); employee.setName("Aarush"); session.save(employee); transaction.commit(); session.close();
Hibernate inserts a zero value in the row when a record is created for the first time. This particular value is increased by one on each update operation.
Once you perform an update operation, hibernate updates the version column as well. The following code shows the same:
Employee employee = new Employee(); employee.setId(1); employee.setName("Aaru"); session.saveOrUpdate(employee);