How to switch off Version

Posted by Anantha Narayanan On 8:57 PM No comments

If you have ever created domain classes and let Grails create the tables, you must have noted that by default there are two columns created. ID and Version.

Why do I have ID and VERSION? 
ID Column is used for creating primary key for the table. VERSION column is used for identifying the version of the record whenever an update is happening to the table.

I will not discuss about the ID column here, but VERSION column requires more elaboration. Grails uses Optimistic locking technique, wherein a row is only locked in the database when the user saves the data after modification.

In a using default scaffolding view, when a user clicks on Edit for a row; Grails will just get a read-only copy of the row (which includes the VERSION column also). If the user does not modify the data, there is no need to release a lock on the record as Grails has not locked the record.

But if the user modifies and clicks on Save; Grails checks the VERSION of record on which the user has modified with the VERSION for that particular row in the database. If both match, Grails updates the modified data to the database. If both VERSION are not the same, Grails knows that some other user (or the same user in a different browser) has modified the record. That could be the only cause for the VERSION being different from the database. Grails simply throws an error message in this case and stops processing.

How can I tell Grails not to create VERSION column?
Now that we have understood why Grails is creating a VERSION column, we will see how to disable this feature. It is in fact very easy to do so.

Consider the domain class below:
 
Package noversion

Class Vehicle {
  String name
  String registrationNo

  static mapping = {
    version false
  }
}

By mentioning "version false" in the mapping closure of the domain class you are telling Grails not to create VERSION column while creating the table.

How Grails updates to table if there is no VERSION column
In the absence of VERSION column, Grails updates the row based only on ID column. The outcome is the table will have values updated by user who has saved last. All other users values gets lost.

The point to note here is that Grails continue to lock using Optimistic locking only.


Related topics:
Coming Soon How to make Grails, use Pessimistic locking instead of Optimistic locking.

0 comments:

Post a Comment

Recommended Post Slide Out For Blogger