Skip to content
Ameen Abozaid
Planned lessonMID-016-L02

Pessimistic locking from JPA

  • Lesson 2 of 7
  • Mid-level
On This Lesson 4 topics

This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.

In this lesson

lock rows from JPA when conflicts are likely.

Planned topics

  • @Lock(LockModeType.PESSIMISTIC_WRITE) on a repository query issues SELECT ... FOR UPDATE.
  • PESSIMISTIC_READ maps to FOR SHARE (verify dialect behavior before recording).
  • Set a lock timeout hint (jakarta.persistence.lock.timeout) so threads do not wait forever.
  • Locks are held to the end of the transaction; keep it short.
Draft outline details

Demonstration

java
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select s from Stock s where s.productId = :id")
Optional<Stock> findForUpdate(Long id);

Check your understanding

When is the lock released?

Show answer

When the transaction commits or rolls back.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.