How to properly lock and reload an object

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);

    // I change the entity itself as well as entites in a relationship.
    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) , , .

!

+5
2

Hibernate-Issue: LockMode.Upgrade .

: Hibernat , . , .

+1

"LockMode.UPGRADE" ? , .

Hibernate . , " , Hibernate , . , ". , SELECT... FOR UPDATE, , .

, "org.hibernate.annotations.CascadeType.LOCK" .

0

All Articles