Version Based Optimistic locking in Hibernate

Posted By : Navjot Chauhan | 09-Dec-2014

Locking is an action taken to prevent data in a relational database from changing between the time it is read and the time that it is used.
e.g.

  1. User 1 loads the Entity for edit.
  2. User 2 loads the same Entity for edit.
  3. User 2 submits form: entity loaded, Updated the fields and saved the entity.
  4. User 1 submits form: entity is loaded, Updated the fields and saved(CONFLICTS occured).

 

There are two Locking strategies given in Hibernate that are Optimistic and Pessimistic. For now we are going to look at Optimistic locking.

 

Hibernate Optimistic locking works when we store the last modified version in a field(e.g. timestamp, long) of an entity and then comparing the latest version of the entity in the session with the entity in the database to see if the change can be saved.

 

For this we need to add a field in our entity, annotated with @Version.

@Entity
@Table(name = 'attendance')
public class Attendance {
	@Id
	private long id;

	@Version
	private int version;

	private String name;

	private String attended;
	...
	...
}

Now this will work like
e.g. Entity at Revision 1

  1. User 1 loads for edit: Revision at 1
  2. User 2 loads for edit: Revision at 1
  3. User 2 submits form: entity (at r1) loaded, Updated the fields and saved the entity: Revision is 2.
  4. User 1 submits form: entity (at r1) is loaded, Updated the fields and the entity not saved(Revision at DB is 2 and we are saving at r1).

 

At this point, after User 2’s update, the row’s version in database is 2, So the user 1's updates will not affects(0 rows) the DB. Hibernate detects that and an org.hibernate.StaleObjectStateException (wrapped in a javax.persistence.OptimisticLockException). To make affect to the DB, User 1 need to refresh the view and then update and save.

Thanks

About Author

Author Image
Navjot Chauhan

Navjot is a bright Groovy and Grails developer and has worked on development of various SaaS applications using Grails framework.

Request for Proposal

Name is required

Comment is required

Sending message..