DEV Community

Ravi Yasas
Ravi Yasas

Posted on

2

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay