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.
- User 1 loads the Entity for edit.
- User 2 loads the same Entity for edit.
- User 2 submits form: entity loaded, Updated the fields and saved the entity.
- 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
- User 1 loads for edit: Revision at 1
- User 2 loads for edit: Revision at 1
- User 2 submits form: entity (at r1) loaded, Updated the fields and saved the entity: Revision is 2.
- 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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Navjot Chauhan
Navjot is a bright Groovy and Grails developer and has worked on development of various SaaS applications using Grails framework.