Showing posts with label hibernate. Show all posts
Showing posts with label hibernate. Show all posts

Thursday, 24 February 2011

JPA and Hibernate: @Version for optimistic locking

What are the possible strategies to handle multiple updates of the same record at the same time?

1. Do Nothing

2. Lock the entire record (pessimistic locking)

3. Optimistic Locking:

Optimistic locking does not use exclusive locks when reading. Instead, a check is made during the update to make sure that the record has not been changed since it was read.  It's often implemented through a single column (of type Timestamp, or Number), used for no other purpose than implementing optimistic concurrency. this column is given a value when the row is inserted. Whenever the record is read, the timestamp column is read as well. When an update is performed, the timestamp column is checked: if it has the same value at UPDATE time as it had when it was read, then the UPDATE is performed and the timestamp is updated as well. If the timestamp value is different at UPDATE time, then an error is returned to the user: they must re-read the record, re-make their changes, and try to update the record again.