Java.Hibernate.Beginner.What is optimistic locking in Hibernate?

Optimistic locking is a concurrency control strategy in Hibernate where multiple transactions can read and update the same data concurrently, but Hibernate checks for conflicts at commit time by comparing a version field.
If another transaction modified the data in the meantime, Hibernate detects the conflict and prevents overwriting by throwing an exception.

🔹 Why use optimistic locking?
✅ It allows high concurrency without holding database locks → best for scenarios where conflicts are rare but possible (e.g., most business systems).
✅ Eliminates blocking and deadlocks caused by pessimistic locks.

🔹 How does it work?

  • You add a @Version field in your entity (e.g., long or Timestamp).
  • Hibernate increments the version each time you update the entity.
  • When you commit, Hibernate checks the version:
    • If the version matches the one originally read → commit proceeds.
    • If the version changed (someone else modified the record) → Hibernate throws an OptimisticLockException.

🔹 Example entity with optimistic locking:

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Version // enables optimistic locking
    private Long version;

    // getters and setters
}

🔹 What happens in the database:
Hibernate uses the version field in UPDATE statements:

UPDATE product
SET name = ?, version = version + 1
WHERE id = ? AND version = ?;

✅ If no rows are updated (because the version no longer matches), Hibernate throws OptimisticLockException.

🔹 Key differences from pessimistic locking:
Optimistic locking → no locks are held → better performance and scalability.
Pessimistic locking → locks records immediately → better for high-conflict scenarios.

🔹 When should you use optimistic locking?
✅ When your use case rarely has simultaneous updates → most web apps, CRUD systems, etc.
✅ When you need concurrency control without sacrificing performance.

🔹 Important note:
Optimistic locking cannot prevent concurrent reads, but it prevents lost updates by detecting write conflicts.

🔹 Important note:
Optimistic locking cannot prevent concurrent reads, but it prevents lost updates by detecting write conflicts.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.