Consider a scenario- 2 applications accessing/updating a single database. one of the applications is using hibernate & has got some records from db, will now process them & save it back. But before it saves, the same set of records is updated by the other application. What will happen in this scenario?
Will hibernate throw an error on saving ? or hibernate will have the intelligence to sync the updated records?
Consider a scenario- 2 applications accessing/updating a single database. one of the applications is
Share
The hibernate will throw
StaleObjectException. Here is why.Hibernate uses optimistic locking to handle database concurrency. A
StaleObjectExceptionis thrown if the data to be updated is modified by another transaction before current transaction commits the changes.EDIT:
and how does hibernate identify that the state of object in memory is stale?
Hibernate uses a version field to track the changes to the entity. This version field updated on every commit. Now if the version number just before commit does not match the version number when the entity was read at the beginning of transaction,
StaleObjectExceptionis thrown.