Implementing Optimistic lock using Hibernate and Spring

JPA/Hibernate Optmistic locking works by using some field to store the last modified version (e.g. timestamp, long) and then comparing the version of the entity in the session with the entity in the database to see if the change can be saved.

For this to work you need to have a field in your entity annotated with @Version.

See below for an example.

http://www.javacodegeeks.com/2012/11/jpahibernate-version-based-optimistic-concurrency-control.html

For this to work in a web application requires further thought however as if two people load the same entity for editing and then some time later submit their edits they will likely both succeed as, unless you are using some kind of long running session, the entity being edited will be reloaded from the database on form submit, populated and saved.

e.g. Entity at Revision 1

  • user 1 loads for edit: revision at 1
  • user 2 loads for edit: revision at 1
  • user 2 submits form: entity (at r1) loaded, fields are bound, entity is saved: revision is 2.
  • user 1 submits form: entity (at r2) is loaded, fields are bound, entity is saved: revision is 3.

So for this to work you could look at submitting a hidden field with the form which stores the entity revision at the time it was loaded. So, on the last step above, when user 1 submits, the revision field will be set back to 1 and the update will fail because the record in the DB as at r2.

Leave a Comment