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
[java]
Book book = Book.get(1)
book.lock()
[/java]
The above code will fire 2 queries one for getting the object and other for taking the lock on it, something like as follows
[java]
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
[/java]
or we can do both the tasks in single go by using the static lock method
[java]
Book book = Book.lock(1)
[/java]
The above code will fire only one query
[java]
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
[/java]
Whenever there is simultaneous updations of an object occurs it throws StaleObjectException.
Hope it helps
Uday Pratap Singh
uday@intelligrape.com