How should I implement optimistic locking in a webapp?
Any feedback is welcome.
I'm using the following frameworks:
- Hibernate 2.1.2
- Spring 1.0.1
- Webwork 2.0
- Velocity 1.3
Here's how I planned on doing it.
1. Set optimistic-lock to version and dynamic-update to true
Code:
<class
optimistic-lock="version"
dynamic-update="true"
/>
The documentation states
Quote:
If you enable dynamic-update, you will have a choice of optimistic locking strategies
2. Add the version tag to the class and create the column in the databaseThe class has a field called version which is used for versioning.
Code:
java.lang.Integer version
Code:
<version
column="version"
name="version"
type="integer"
unsaved-value="null"
/>
If the field is null it means we have a transient object which needs to be saved.
3. Add version and id to the HTML formCode:
<input type="text" name="name" value="$!object.name"/>
<input type="hidden" name="id" value="$!object.id"/>
<input type="hidden" name="version" value="$!object.version"/>
I'm using Velocity so if the object is null the id and version fields would be null and
a new object would be inserted by hibernate.
4. Read version and id in WebWork2 actionWhen the user submits the data to the action I get the id and version
and create the object as follows.
Code:
Object object = new Object();
object.setVersion(version);
object.setId(version);
object.setName(name);
I then call:
Code:
session.saveOrUpdate(object);
saveOrUpdate would insert a new object into the database if id and version are null.
Or update the existing object if id and version are set to non-null values.
5. Hibernate takes care of the rest
Hibernate increments the version number and checks that a non stale object is being updated.
If the database contains version 15 of object and user submits data with version 0 hibernate will
detect this and throw a StaleObjectException.