File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Optimistic & Pesimistic locking Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Optimistic & Pesimistic locking " Watch "Optimistic & Pesimistic locking " New topic

Optimistic & Pesimistic locking

Saumya Nair
Ranch Hand

Joined: Apr 25, 2006
Posts: 34
What is Optimistic and Pesimistic Locking in Hibernate.When to use such locking mechanism ???
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

Optimistic locking is a technique where you allow your application to perform updates hoping there won't be any simultaneous updates from another process, hence optimistic. Pessimistic locking is the technique where you assume there will be simultaneous updates from another process so you lock the data you are changing before any changes take place.

In Hibernate, optimistic locking is provided fairly seemlesly. You add a version field to your table and a version element to your mapping file. When you update a Hibernate object Hibernate will check the version values match. If they do the update is successful, and the version is incremented, if they are not Hibernate throws a StaleObjectException and you know that something else has updated your data.

Pessimistic locking is provided by specifying a LockMode when you get an object from the database. If you get your object with the LockMode.UPGRADE for example Hibernate will use database specific SQL to lock the record (if your database supports it) such as "select ... for update". Now nothing can update that record till you are finished.

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Saumya Nair
Ranch Hand

Joined: Apr 25, 2006
Posts: 34
Thanks Paul
I agree. Here's the link:
subject: Optimistic & Pesimistic locking
It's not a secret anymore!