Wednesday, January 25, 2012

Hibernate: Dealing with Optimistic Locking

Overview:
This article looks at ways of you can deal with optimistic locking in Hibernate.

Optimistic Locking:
Technique used to avoid concurrent access to change a persistant entity. For long transactions or invocations that span several database transactions, it is useful to store versioned data to ensure that if the same entity is updated by two conversations, the last to commit changes will be informed and not override the other conversation's work.

There are two ways to achieve this.
  • Version numbers
  • Timestamp
Version numbers
To use version numbers, you need to define a numeric field in the entity class to enable this as follows,
 public class Person {
private int version;
. . .
}
Then, in the Hibernate mapping file you need to designate this field as the versioning field as follows,
 <hibernate-mapping>
<class name="Person" table="PERSON">
<version name="version" column="VERSION_ID" access="field" />
. . .
</class>
</hibernate-mapping>
Hibernate will handle the versioning each time the persistent entity is loaded.

NOTE
: Here, we limit the access to 'field'. The reason being, we don't want this to be exposed using getters/setters because this is ONLY for the purpose of versioning but nothing to do with the application's logic. Since we don't have getters/setters, we need to tell Hibenate to access this using the field.

Timestamp
Here, for the field you use a Date field in the entity class.
 import java.util.Date; 
public class Person {
private Date lastUpdatedTimestamp;
. . .
}
Following is the corresponding Hibernate mapping file,
 <hibernate-mapping>  
<class name="Person" table="PERSON">
<timestamp name="lastUpdatedTimestamp" column="LASTUPDATED_TIMESTAMP" access="field" />
. . .
</class>
</hibernate-mapping>

No comments:

Post a Comment