Hibernate / EclipseLink Interview questions
Why should you use @Version for optimistic locking instead of manual version checks?
It's technically possible to hand-roll optimistic locking by adding your own version or timestamp column and manually checking it before every update, but that approach has to be reimplemented correctly, and consistently, everywhere an update can happen, which is both error-prone and easy to forget in a new code path.
@Version hands that entire responsibility to EclipseLink: the version field is automatically included in the WHERE clause of every generated UPDATE, automatically incremented on every successful update, and automatically checked for the zero-row-affected case that signals a conflict, raising OptimisticLockException consistently, regardless of which code path triggered the update.
This consistency matters most in larger codebases with many different services or code paths that can modify the same entity; a manually implemented check only protects the specific code path someone remembered to add it to, while @Version protects every update path uniformly, including ones added later by developers who may not even be aware optimistic locking is in use.
More Related questions...