Pessimistic locking in Grails

03 / Sep / 2012 by Uday Pratap Singh 0 comments

We already know that by default Grails scaffold comes with Optimistic locking and it is achieved by version field. Now lets see how Pessimistic locking is achieved in Grails.
Grails has a built in method to acquire lock on object. To acquire a lock we will do something like following

Book book = Book.get(1)
book.lock()

The above code will fire 2 queries one for getting the object and other for taking the lock on it, something like as follows

Hibernate: select book0_.id as id1_0_, book0_.version as version1_0_, book0_.name as name1_0_, book0_.price as price1_0_ from book book0_ where book0_.id=?
Hibernate: select id from book where id =? and version =? for update

or we can do both the tasks in single go by using the static lock method

Book book = Book.lock(1)

The above code will fire only one query

Hibernate: select book0_.id as id1_0_, book0_.version as version1_0_, book0_.name as name1_0_, book0_.price as price1_0_ from book book0_ where book0_.id=? for update

Whenever there is simultaneous updations of an object occurs it throws StaleObjectException.

 

Hope it helps
Uday Pratap Singh
uday@intelligrape.com

FOUND THIS USEFUL? SHARE IT

Leave a comment -