Optimistic locking strategy in Grails

01 / Sep / 2012 by Uday Pratap Singh 0 comments

In Grails optimistic locking is achieved by version property . The Grails Domain classes has a built in property called “version”. This property can be used for optimistic locking. Although you can remove this property
[java]
static mapping ={
version false
}
[/java]
but its not a very good practice. The initial value of version field is 0 and Grails automatically increments it by 1 every time the object is updated. This property helps to identify whether the currently updating object has already been updated or not.

 

Suppose we have a Book domain and its corresponding BookController the default Grails scaffold update action has code something like as follows
[java]
if (version != null) {
if (book.version > version) {
book.errors.rejectValue("version", "default.optimistic.locking.failure",
[message(code: ‘book.label’, default: ‘Book’)] as Object[],
"Another user has updated this Book while you were editing")
render(view: "edit", model: [book: book])
return
}
}
[/java]
As we can see it checks the current version of the object with the version got from request. If the current version of object is greater, it injects the error into the object and object is not saved.

 

Hope it helps
Uday Pratap Singh
uday@intelligrape.com

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *