You can disable Hibernate's automatic version increment for particular properties and collections by setting the
optimistic-lock mapping attribute to
false. Hibernate will then no longer increment versions if the property is dirty.
Legacy database schemas are often static and cannot be modified. Or, other applications might access the same database and will not know how to handle version numbers or even timestamps. In both cases, versioning cannot rely on a particular column in a table. To force a version check with a comparison of the state of all fields in a row but without a version or timestamp property mapping, turn on
optimistic-lock="all" in the
<class> mapping. This conceptually only works if Hibernate can compare the old and the new state (i.e., if you use a single long
Session and not session-per-request-with-detached-objects).
Concurrent modification can be permitted in instances where the changes that have been made do not overlap. If you set
optimistic-lock="dirty" when mapping the
<class>, Hibernate will only compare dirty fields during flush.
In both cases, with dedicated version/timestamp columns or with a full/dirty field comparison, Hibernate uses a single
UPDATE statement, with an appropriate
WHERE clause, per entity to execute the version check and update the information. If you use transitive persistence to cascade reattachment to associated entities, Hibernate may execute unnecessary updates. This is usually not a problem, but on update triggers in the database might be executed even when no changes have been made to detached instances. You can customize this behavior by setting
select-before-update="true" in the
<class> mapping, forcing Hibernate to
SELECT the instance to ensure that changes did occur before updating the row.