首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >弹簧数据CrudRepository与悲观锁

弹簧数据CrudRepository与悲观锁
EN

Stack Overflow用户
提问于 2016-11-11 09:48:48
回答 1查看 16.4K关注 0票数 28

我在用

  • 弹簧启动1.4.2
  • 春季数据JPA 1.10.5
  • PostgreSQL 9.5数据库

我希望在我的Spring数据存储库中有一个带有悲观锁的findOne方法,它与已经提供的findOne方法是分开的。

this answer之后,我写道:

代码语言:javascript
复制
public interface RegistrationRepository extends CrudRepository<Registration, Long> {
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select r from Registration r where r.id = ?1")
    Registration findOnePessimistic(Long id);
}

这几乎成功了。

不幸的是,这不会在实体管理器缓存中刷新我的实体的先前实例。我有两个并发请求更新我的注册状态。

  • 第二个等待第一个提交的事务。
  • 第二个是,而不是,它考虑了第一个更改。

从而破坏了行为。

知道为什么@Lock不立即刷新实体管理器吗?

更新

下面是请求的示例代码:

代码语言:javascript
复制
public interface RegistrationRepository extends CrudRepository<Registration, Long> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select r from registration_table r where r.id = ?1")
    Registration findOnePessimistic(Long id);

}

public void RegistrationService {

    @Transactional
    public void doSomething(long id){
        // Both threads read the same version of the data 
        Registration registrationQueriedTheFirstTime = registrationRepository.findOne(id);

        // First thread gets the lock, second thread waits for the first thread to have committed
        Registration registration = registrationRepository.findOnePessimistic(id);
        // I need this to have this statement, otherwise, registration.getStatus() contains the value not yet updated by the first thread
        entityManager.refresh(registration);

        registration.setStatus(newStatus);
        registrationRepository.save(registration);
    }
}
EN

回答 1

Stack Overflow用户

发布于 2017-06-01 12:37:56

您需要使用Spring为您创建的Spring

代码语言:javascript
复制
    @Transactional
    public void doSomething(long id){
        // Both threads read the same version of the data 
        Registration registrationQueriedTheFirstTime = registrationRepository.findOne(id);

        // First thread gets the lock, second thread waits for the first thread to have committed
        Registration registration = registrationRepository.findOnePessimistic(id);
        // I need this to have this statement, otherwise, registration.getStatus() contains the value not yet updated by the first thread
        entityManager.refresh(registration);

        EntityManager em = EntityManagerFactoryUtils.getTransactionalEntityManager(<Your entity manager factory>);
        em.refresh(registration);
        registration.setStatus(newStatus);
        registrationRepository.save(registration);
    }

}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40545248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档