What is optimistic locking?
Optimistic locking is a method used to prevent simultaneously access problem on the same entity for change, which does not lock on the database level, in order to maintain the correct data.
For example, if two user wants to update same entity in different transactions, when first one saves and then second one saves without getting updates from the first user’s change, who will be the winner?
Most of the web applications, like ours, has such cases: Two users retrieve and modify a data on the page, then first user saves the data a transcation and then second user modifies and saves the data in an another transacion. Here are 3 alternatives:
1. Last commit wins : Both updates are performed, the second user overwrites without seeing the first user changes and without any error message
2. First commit wins : (Optimistic Locking) The update is performed, but second user gets error message, requiring restart of the processes on the first users changes.
3. Merge conflicting update : The second user are prompted to merge changes.
Automatic Versioning
Hibernate provides automatic versioning for options 2 and 3, using a version field managed by hibernate.
Versioning with integer version
public class MyClass {
...
private int version;
...
}
<class name="MyClass">
<id ...>
<version name="version" column="VERSION" access="field">
...
</class>
Versioning with timestamp
public class MyClass {
...
private int lastModifyDataTime;
...
}
<class name="MyClass">
<id ...>
<timestamp name="lastModifyDataTime" column="LAST_MODIFIY_DATE_TIME" access="field">
...
</class>
Automatic versioning is handled by hibernate, you don’t need to update versions/timestamps.
Considering the example mentioned above, when second user saves, hibernate finds this user is working on the stale data and throws StaleObjectException.
You can catch this exception, and rethrow your own exception. By the way, if you’re using Hibernate with Spring, this exeception is wrapped with HibernateOptimisticLockingFailureException.
One more point, you should be aware of that hibernate ignores the versioning when getting object and updating fields and then version are in the same session.