11.3.4. Customizing automatic versioning
You may 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 can't be modified. Or, other applications might also access the same database and don't know how to handle version numbers or even timestamps. In both cases, versioning can't rely on a particular column in a table. To force a version check without a version or timestamp property mapping, with a comparison of the state of all fields in a row, turn on optimistic-lock="all"
in the <class>
mapping. Note that this concepetually only works if Hibernate can compare the old and new state, i.e. if you use a single long Session
and not session-per-request-with-detached-objects.
Sometimes concurrent modification can be permitted as long as the changes that have been made don't 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 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 might execute uneccessary 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 actually occur, before updating the row.