gpt4 book ai didi

java - Spring数据CrudRepository和悲观锁

转载 作者:IT老高 更新时间:2023-10-28 13:47:46 24 4
gpt4 key购买 nike

我正在使用

  • Spring Boot 1.4.2
  • Spring Data JPA 1.10.5
  • PostgreSQL 9.5 数据库

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

关注 this answer我写道:

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 不能立即刷新实体管理器吗?

更新

这是请求的示例代码:

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

最佳答案

您需要使用 Spring 为您创建的 entity Manager 事务:

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

}

关于java - Spring数据CrudRepository和悲观锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40545248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com