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
@Entity @org.hibernate.annotations.Entity( ................. 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.