作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在使用
我希望在我的 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/
我正在编写一个 Web 应用程序,两个不同的用户可以在其中更新事物列表,例如待办事项列表。我已经意识到,乐观锁定机制效果最好,因为我不希望出现高争用情况。 我一直在查看事务隔离级别,现在我有点困惑。看
我是一名优秀的程序员,十分优秀!