【发布时间】:2017-03-25 12:32:53
【问题描述】:
我正在使用
- 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);
}
}
【问题讨论】:
-
您必须向我们展示代码,它会更改实体值。为什么在只读取实体的方法上使用“PESSIMISTIC_WRITE”锁定表?
-
我在注解为
@Transactional的方法中使用代码,在该方法中我读取实体,更新它,然后将其写回。相当标准。我想避免这个操作的并发,所以我想使用悲观锁。我只想在update之前做select for update。 -
整个代码块是事务性的,因此使用相同的实体管理器。
EntityManager充当一级缓存。您首先在没有锁定的情况下检索对象,然后再次使用锁定再次检索它。但是由于一级缓存,您将检索该对象而不是新的数据库对象。这基本上就是EntityManager的工作原理,如果您不希望您首先必须clear实体管理器。或者更确切地说,为什么您首先在没有锁定同一 tx 的情况下检索它(这很奇怪,恕我直言)。 -
我希望
CrudRepository从一级缓存中清除该实体,以防我指定悲观锁... -
问题不是关于悲观锁定在我的情况下的相关性,问题是关于为什么 Spring-Data-JPA 不使用数据库中锁定的值刷新缓存...仅供参考我使用悲观锁定,因为对我的状态更新(例如发送电子邮件)有副作用,无法回滚。
标签: java spring spring-data spring-data-jpa