LockOptions, Session.buildLockRequest() and LockRequest in Hibernate
February 15, 2015
In this page we will learn LockOptions, Session.buildLockRequest() and LockRequest in hibernate. LockOptions represents different lock mode to lock entity object using Session.buildLockRequest(). This method returns LockRequest and using its method lock() we can lock the entity instance. Find the code snippet.
Student s = new Student(3, 22,"Ram"); LockRequest lockRequest = session.buildLockRequest(LockOptions.READ); lockRequest.lock(s);
Session.buildLockRequest() A session method that builds Lock Request. This method accepts lock mode to build lock request.
LockRequest : This is the inner class of Session. Using lock() method we lock the entity object.
Lock Object in READ Mode Demo
In this example, we will lock an entity in READ mode. Try to read data for the entity and we will be able to read. Use Session.refresh() to re-read the data.ReadData.java
package com.concretepage; import org.hibernate.LockOptions; import org.hibernate.Session; import org.hibernate.Session.LockRequest; public class ReadData { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); LockRequest lockRequest = session.buildLockRequest(LockOptions.READ); Student s = (Student) session.load(Student.class, new Integer(1)); lockRequest.lock(s); //re-read the object session.refresh(s); session.getTransaction().commit(); session.close(); } }
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from student student0_ where student0_.id=? Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from student student0_ where student0_.id=?
SaveData.java
package com.concretepage; import org.hibernate.LockOptions; import org.hibernate.Session; import org.hibernate.Session.LockRequest; public class SaveData { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Student s = new Student(3, 22,"Ram"); session.beginTransaction(); LockRequest lockRequest = session.buildLockRequest(LockOptions.READ); lockRequest.lock(s); //Unable to save as object is locked in read mode. session.save(s); session.getTransaction().commit(); session.close(); } }
Hibernate: select id from student where id =? Exception in thread "main" org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.concretepage.Student#3] at org.hibernate.dialect.lock.SelectLockingStrategy.lock(SelectLockingStrategy.java:93)