弹簧数据 Crud存储库和悲观锁
2022-09-01 14:47:42
我正在使用
- 弹簧靴 1.4.2
- 春季数据 JPA 1.10.5
- PostgreSQL 9.5 database
我希望在我的Spring Data存储库中有一个具有悲观锁的方法,该方法与已经提供的方法分开。findOne
findOne
按照这个答案,我写道:
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);
}
}