Optimistic Locking in Hibernate and JPA

When writing applications that are going to be accessed by more than one user at a time, you run the risk of the underlying data being corrupted. One solution to this problem is to implement row locks on the data being modified. However, should a process or a user be modifying several rows, this lock can lead to performance degradation as the DB begins to wait for locks to be released.

A better solution is to use Optimistic Locking. This is where we monitor the row being modified and allow other users to access it. No lock is being applied here. However, once the row has been saved back to the database, all the rows that are still being viewed become out-of-date, or stale.

The simplest method by which the row can be monitored is to employ a “version” column. This is a simple counter that increments every time an update is performed on the row.

In JPA annotations this is represented by the @Version annotation.

@Version
@Column(name = "version", nullable = false, length = 5)
public int getVersion() { ... }

Now, when this object is saved the version number is automatically incremented. Hibernate will take care of this for us. When a save is attempted on a stale object, Hibernate will throw a StaleObjectStateException (wrapped in a HibernateOptimisticLockingFailureException).
=======================================================
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.

Comments

Popular posts from this blog

API design best practices

DB Connection Issues

Reading Excel Sheet on client side and processing it