我正在使用:
- Spring Boot 1.4.2
- Spring Data JPA 1.10.5
- PostgreSQL 9.5 数据库
我想在我的 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);
}
}
@Transactional
的方法中使用代码,读取实体,更新它并将其写回。非常标准。我想避免此操作上的并发,因此我想使用悲观锁。我只想在update
之前执行select for update
。 - rcomblenCrudRepository
从一级缓存中清除该实体。 - rcomblen