This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Optimistic & Pesimistic locking " Watch "Optimistic & Pesimistic locking " New topic
Author

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
Bartender

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
 
wood burning stoves
 
subject: Optimistic & Pesimistic locking