Hibernate / EclipseLink Interview questions
What is optimistic locking in EclipseLink and JPA?
Optimistic locking detects conflicting concurrent updates to the same row without holding a database lock for the duration of a transaction. A version column, mapped with @Version, is incremented on every update; when EclipseLink issues an update, it includes the version value read at load time in the WHERE clause, and if no row matches (because someone else already updated it and bumped the version), EclipseLink throws an OptimisticLockException.
@Entity public class Account { @Id private Long id; @Version private int version; private BigDecimal balance; }
This approach assumes conflicts are rare and avoids the throughput cost of holding real database locks; when a conflict does occur, it's surfaced as an exception the application has to handle, typically by reloading the entity and retrying the operation.
More Related questions...