Working with the versioning of objects

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.

Getting ready

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.

Creating the classes

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
}

Creating the tables

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`)
);

How to do it…

Here, we will insert a record and see the table data after a successful insertion. Update the following code:

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();

Output

Hibernate: insert into employee (name, version) values (?, ?)

The following employee table shows a database table structure after saving one record:

id

name

version

1

Aarush

0

How it works…

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:

Code

Employee employee = new Employee();
employee.setId(1);
employee.setName("Aaru");
session.saveOrUpdate(employee);

Output

Hibernate: update employee set name=?, version=? where id=? and version=?

The following data table shows the data after an update:

id

name

version

1

Aaru

1

Once we update an employee name here, hibernate increases the version number.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.26.108