Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is optimistic lock in JPA?

I am new to JPA. And I came down to this annotation @Version. In the documentation for this annotation it says:

"This annotation specifies the version field or property of an entity class that serves as its optimistic lock value. The version is used to ensure integrity when performing the merge operation and for optimistic concurrency control. "

What does it mean by optimistic lock and how it is actually related to this annotation? Thanks

like image 301
Hossein Avatar asked Feb 12 '13 14:02

Hossein


Video Answer


1 Answers

Long story short...

Each record of an entity with a field annotated as @Version is tagged with a version like in SVN. Whenever the entity is updated by commiting (and flushing!) a transaction a check ensures the versions of your current entity and the entry in the database match. A failure in this check results in an OptimisticLockException, because someone commited a change on that registry before the current operation did.

Optimistic is based in the concept of

"I do not need to lock this entry, nobody will touch it"

while a Pessimistic lock actually locks certain operations (Like READ or WRITE) on a given entry assuming

"Someone will try to update this entity while I work"

like image 164
Fritz Avatar answered Sep 23 '22 04:09

Fritz