Posts Tagged ‘Hibernate’

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 Stumble It! Submit to Slashdot Submit to Buzz! Digg It!

What have I begun?

Written by Cabiri. Posted in Cabiri-Blog

The purpose of this blog is to capture useful tid-bits for Java, Flex, Spring, Hibernate, Cairngorm, LiveCycle DS, etc. and place them here for easy access (mainly by me). Years of development have shown me a whole slew of interesting and useful pieces aspects of code, many of which I promptly forgot. I hope here to focus on these more obscure bits of information, as well as useful gotchas and how-tos. This should then allow me to remember everything, and possibly help others in similar positions. Posts will be infrequent, as and when I find something handy, I’ll try to keep random streams of consciousness to a minimum, and will endeavour to avoid any inflammatory remarks.

RSS Feed Add to Technorati Favorites Add to Stumble It! Submit to Slashdot Submit to Buzz! Digg It!