首页 > 解决方案 > 使用 pessimistic_write 锁查找和更新不能防止乐观锁失败?

问题描述

我尝试使用 pessimistic_write 锁来查找和更新一条记录,如下所示,

transactionService.executeTransaction(() -> {
    Entity newEntity = em.find(entityClass, id, LockModeType.PESSIMISTIC_WRITE);
    newEntity = setEntityWithProperty.setEntity(newEntity, property);
});

我在 Spring 中使用 transactionTemplate。实体本身有一个版本字段来使用乐观锁。使用 pessimistic_write 锁,在事务期间(查找然后更新),其他线程应该无法读取或写入记录,对吧?但是当提交事务时,我仍然可以得到 OptimisticLockFailuerException。为什么会发生这种情况?

标签: spring-dataoptimistic-lockingpessimistic-locking

解决方案


推荐阅读