What is an optimistic locking in Hibernate?

Optimistic locking is a concurrency-control strategy in Hibernate that assumes conflicts are rare and detects them at commit time rather than blocking other transactions upfront, using a version column to spot concurrent modifications.

Key Points: • A field annotated with @Version (typically an int, long, or timestamp) is automatically incremented by Hibernate on every update. • Before committing an update, Hibernate compares the version it read with the current version in the database; a mismatch throws OptimisticLockException. • It avoids the overhead of database locks, making it well-suited to read-heavy applications with infrequent write conflicts. • Unlike pessimistic locking, it doesn't block other transactions from reading or attempting to write — conflicts surface only when a write actually collides. • Applications typically catch OptimisticLockException and retry the operation or surface a "please refresh and try again" message to the user.

Example: Two clerks open the same Product record to edit its price; whichever one saves first bumps the version from 3 to 4, and when the second clerk tries to save based on version 3, Hibernate throws an OptimisticLockException instead of silently overwriting the first clerk's update.

Code Example:

@Entity
public class Product {
    @Id
    private Long id;

    @Version
    private int version;

    private BigDecimal price;
}

Interview Tip: A concise interview answer is:

"Optimistic locking uses a @Version field that Hibernate increments on every update; before committing, it checks the version you loaded still matches the database, and throws an OptimisticLockException if not, which lets concurrent edits be detected without holding database locks the whole time."