Wednesday, October 17, 2012

Hibernate automatic versioning - Part 1

Hibernate can provide automatic versioning for the entities without you doing ANYTHING. By WITHOUT ANYTHING I really mean WITHOUT  ANYTHING ! You just have your entity classes and you wnat hibernate to provide versioning so that an update on a already changes object would not happen. This sounds exciting but in actual practise its not that very used. We'll see how and why.

If you simply want hibernate to provide automatic versioning (without addition of version column or timestamp in the correspoding table and entity) then hibernate can do this but the caveat is that object should be retrieved and modified in the same session or persistence context. This essentially means that the session must not be closed (it can be flushed though to send the changes to database).

When using this feature, Hibernate checks the current database state of the entity in question and if the earlier state ( when it was retrieved or when the last flush operation was called upon session) is different from the current database state, it concludes that the entity has been modified and throws StaleObjectException.

To enable this feature on an entity you will have to add attribute optimistic-lock="all" in the entity mapping if you are using xml based configuration or Hibernate specific annotation like below if you are using annotation approach

        optimisticLock = OptimisticLockType.ALL,

public class TestEntity{ ... }

Hibernate team does not recommend using this automatic versioning without version or timestamp column as this is bit slow and complex. Also another bigger disadvantage is that it does not work for detached objects. It works only as long as the session is not closed. For this reason too, this is not effective in long running conversations as well.

 In the next part I will explain about other better way of adding optimistic version control to your entities which uses version or timestamp column to keep track of the entity state.

No comments:

Post a Comment