In my web application, I have several threads that can potentially access the same data at the same time, so I decided to implement optimistic (version) and pessimistic locking using Hibernate.
Currently, I am using the following template to lock an object and perform write operations on it (using Springs transaction manager and transaction demarcation using @Transactional):
@Transactional
public void doSomething(entity) {
session.lock(entity, LockMode.UPGRADE);
session.refresh(entity);
entity.setBar(...);
for(Child childEntity : entity.getChildren()) {
childEntity.setFoo(...);
}
}
However, sometimes I get StaleObjectExceptionwhen @Transactional performs a reset, which tells me that ChildEntity was modified at the same time and now has the wrong version.
, entity , . - , ? () session.lock(entity, LockMode.READ) , , .
!