DEV Community

Ravi Yasas
Ravi Yasas

Posted on

Hibernate Optimistic locking and Pessimistic locking

Optimistic locking

  • When two threads are going to update the same data at the same time, conflict can happen.
  • There are two options to handle this, Versioned and Version-less.

Versioned Optimistic locking

  • In this case, @Version annotation can be used.
  • @Version annotation allows Hibernate to activate the optimistic locking whenever executing an UPDATE and DELETE statements.
@Entity@Table(name = "orders")    
public class Order {
   @Id
   private long id;

   @Version
   private int version;

   private String description;
   private String status;

}
Enter fullscreen mode Exit fullscreen mode

Version-less Optimistic locking

  • But in this approach, it considers the entity as a whole unit.
  • If you change two fields at the same time, then It will throw an ObjectOptimisticLockingFailureException.
  • To handle this we can use simply version-less optimistic locking.
  • This can be achieved by using @OptimisticzLocking and @DynamicUpdate annotations.
@Entity
@OptimisticLocking(type = OptimisticLockType.DIRTY)
@DynamicUpdate
public class VersionlessProduct {
    @Id
    private UUID id;
    private String name;
    private int stock;
}
Enter fullscreen mode Exit fullscreen mode

Pessimistic locking

  • This can be implemented by @Lock annotation
interface WidgetRepository extends JPARepository<Widget, Long> {

   @Lock(LockModeType.PESSIMISTIC_WRITE)
   Widget findOne(Long id);
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)