Posts Tagged ‘JPA’

Optimistic Locking in Hibernate and JPA

Written by Cabiri. Posted in Hibernate

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).

RSS Feed Add to Technorati Favorites Add to Del.icio.us Stumble It! Submit to Slashdot Submit to Buzz! Digg It!