删除实体时避免 StaleObjectStateException

发布于 2024-12-10 20:56:14 字数 1880 浏览 0 评论 0原文

我有 2 个并发线程,它们同时进入(Spring)事务服务。

使用 Hibernate,服务方法加载一些实体,处理这些实体,找到一个实体并将其从数据库中删除。伪代码如下:

@Transactional
public MyEntity getAndDelete(String prop) {
    List<MyEntity> list = (List<MyEntity>)sessionFactory
        .getCurrentSession()
        .createCriteria(MyEntity.class)
        .add( Restrictions.eq("prop", prop) )
        .list();

    // process the list, and find one entity
    MyEntity entity = findEntity(list);
    if (entity != null) {
        sessionFactory.getCurrentSession().delete(entity);
    }
    return entity;
}

如果两个线程同时传递相同的参数,两个线程都会“找到”相同的实体,并且都会调用delete。当会话关闭时,其中之一将失败并抛出org.hibernate.StaleObjectStateException

我希望两个线程都会返回实体,不会抛出任何异常。为了实现这一点,我尝试在删除实体之前锁定(使用“select...for update”)实体,如下所示:

@Transactional
public MyEntity getAndDelete(String prop) {
    List<MyEntity> list = (List<MyEntity>)sessionFactory
        .getCurrentSession()
        .createCriteria(MyEntity.class)
        .add( Restrictions.eq("prop", prop) )
        .list();

    // process the list, and find one entity
    MyEntity entity = findEntity(list);
    if (entity != null) {
        // reload the entity with "select ...for update"
        // to ensure the exception is not thrown
        MyEntity locked = (MyEntity)sessionFactory
            .getCurrentSession()
            .load(MyEntity.class, entity.getId(), new LockOptions(LockMode.PESSIMISTIC_WRITE));
        if (locked != null) {
            sessionFactory.getCurrentSession().delete(locked);
        }
    }
    return entity;
}

我使用 load() 而不是 get() 因为根据 hibernate API,如果实体已在会话中,则 get 将返回实体,而 load 应重新读取它。

如果两个线程同时进入上述方法,其中一个线程会阻塞锁定阶段,并且当第一个线程关闭事务时,第二个线程将被唤醒并抛出 org.hibernate.StaleObjectStateException 。为什么?

为什么锁定加载不只是返回 null?我怎样才能做到这一点?

I have 2 concurrent threads that at the same time enter a (Spring) transaction service.

Using Hibernate, the service method loads some entities, processes those, finds one and deletes it from the DB. The pseudo code is as following:

@Transactional
public MyEntity getAndDelete(String prop) {
    List<MyEntity> list = (List<MyEntity>)sessionFactory
        .getCurrentSession()
        .createCriteria(MyEntity.class)
        .add( Restrictions.eq("prop", prop) )
        .list();

    // process the list, and find one entity
    MyEntity entity = findEntity(list);
    if (entity != null) {
        sessionFactory.getCurrentSession().delete(entity);
    }
    return entity;
}

In case two threads at the same time pass the same parameter, both will "find" the same entity an both will call delete. One of them will fail throwing an org.hibernate.StaleObjectStateException when the session is close.

I would like that both threads would return the entity, with no exception being thrown. In order to achieve this, I tried to lock (with "select... for update") the entity before deleting it, as following:

@Transactional
public MyEntity getAndDelete(String prop) {
    List<MyEntity> list = (List<MyEntity>)sessionFactory
        .getCurrentSession()
        .createCriteria(MyEntity.class)
        .add( Restrictions.eq("prop", prop) )
        .list();

    // process the list, and find one entity
    MyEntity entity = findEntity(list);
    if (entity != null) {
        // reload the entity with "select ...for update"
        // to ensure the exception is not thrown
        MyEntity locked = (MyEntity)sessionFactory
            .getCurrentSession()
            .load(MyEntity.class, entity.getId(), new LockOptions(LockMode.PESSIMISTIC_WRITE));
        if (locked != null) {
            sessionFactory.getCurrentSession().delete(locked);
        }
    }
    return entity;
}

I use load() instead of get() since according to the hibernate APIs, get would return the entity if already in the session, while load should re-read it.

If two threads enter at the same time the method above, one of them blocks a the locking stage, and when the first thread closes the transaction, the second is awoken throwing an org.hibernate.StaleObjectStateException. Why?

Why does the locked load not just return null? How could I achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

揽月 2024-12-17 20:56:15

我花了一些时间调查这个问题,终于明白发生了什么。

PESSIMISTIC_WRITE 锁尝试“锁定”已在会话中加载的实体,它不会从数据库重新读取对象。调试调用时,我看到 entity ==locked 返回了 true (用 Java 术语来说)。两个变量都指向同一个实例。

要强制休眠重新加载实体,必须首先将其从会话中删除。

下面的代码可以解决这个问题:

@Transactional
public MyEntity getAndDelete(String prop) {
    List<MyEntity> list = (List<MyEntity>)sessionFactory
        .getCurrentSession()
        .createCriteria(MyEntity.class)
        .add( Restrictions.eq("prop", prop) )
        .list();

    // process the list, and find one entity
    MyEntity entity = findEntity(list);
    if (entity != null) {

        // Remove the entity from the session.
        sessionFactory.getCurrentSession().evict(entity);

        // reload the entity with "select ...for update"
        MyEntity locked = (MyEntity)sessionFactory
            .getCurrentSession()
            .get(MyEntity.class, entity.getId(), new LockOptions(LockMode.PESSIMISTIC_WRITE));
        if (locked != null) {
            sessionFactory.getCurrentSession().delete(locked);
        }
    }
    return entity;
}

PESSIMISTIC_WRITE 必须与 get 一起使用,而不是与 load 一起使用,否则会抛出 org.hibernate.ObjectNotFoundException

I spent some time investigating this issue and I finally understood what happens.

The PESSIMISTIC_WRITE lock tries to "lock" the Entity that is already loaded in the session, it does not re-read the object from the DB. Debugging the call, I saw that entity == locked returned true (in Java terms). Both variables were pointing to the same instance.

To force hibernate to reload the Entity, it must be removed from the session first.

The following code does the trick:

@Transactional
public MyEntity getAndDelete(String prop) {
    List<MyEntity> list = (List<MyEntity>)sessionFactory
        .getCurrentSession()
        .createCriteria(MyEntity.class)
        .add( Restrictions.eq("prop", prop) )
        .list();

    // process the list, and find one entity
    MyEntity entity = findEntity(list);
    if (entity != null) {

        // Remove the entity from the session.
        sessionFactory.getCurrentSession().evict(entity);

        // reload the entity with "select ...for update"
        MyEntity locked = (MyEntity)sessionFactory
            .getCurrentSession()
            .get(MyEntity.class, entity.getId(), new LockOptions(LockMode.PESSIMISTIC_WRITE));
        if (locked != null) {
            sessionFactory.getCurrentSession().delete(locked);
        }
    }
    return entity;
}

The PESSIMISTIC_WRITE mut be used with get instead of load, because otherwise a org.hibernate.ObjectNotFoundExceptionwould be thrown.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文