我在我的项目中使用Spring,并计划采用乐观的锁定机制。但是我还没有见过Spring可以使用乐观锁。
我有一个具体的例子,据我所知,在读取和更新多个事务时,可序列化隔离无法涵盖这种情况。
我使用的是Cockroach数据库,它只支持可序列化的隔离。下面是我习惯于与数据库交互的两个函数:
@Getter
@Setter
@NoArgsConstructor
@Entity(name = "account")
@DynamicUpdate
@ToString
public class AccountEntity {
@Id
@Column(columnDefinition = "UUID")
private UUID id;
@NotNull
@Column(name = "status")
@Enumerated(EnumType.STRING)
private Status status;
@Version
private Long version;
}帐户实体
public AccountDto getAccount(UUID id) {
AccountEntity entity = this.accountRepository.findById(id).orElseThrow();
return new AccountDto(entity.getId(), entity.getStatus());
}获取API
@Transactional
public AccountDto updateAccount(UUID id, @Valid Long sleep,
@Valid AccountUpdateDto accountUpdateDto) {
log.info("Start updating status [{}] for the account {}.", accountUpdateDto.getStatus(), id);
AccountEntity entity = this.accountRepository.findById(id).orElseThrow();
entity.setStatus(accountUpdateDto.getStatus());
AccountDto accountDto = new AccountDto(id, accountUpdateDto.getStatus());
log.info("Finish updating status [{}] for the account {}.",
accountUpdateDto.getStatus(), id);
return accountDto;
}放置API
在图像中,我希望抛出一个OptimisticLockException。但是当用户1更新帐户时,它仍然可以正常地更新帐户。因为在updateAccount方法中,找到了帐户的最新版本。它不能发生OptimisticLockException。
那么在什么情况下它可以抛出一个OptimisticLockException呢?
发布于 2022-11-17 07:43:55
当事务从看到某些数据的版本A开始,然后看到该数据的不同版本A‘时,乐观锁定就会生效。
但是,当您状态下,Cockroach使用事务隔离级别可序列化。这意味着对于每个事务,似乎没有其他事务同时运行。因此,上述情况不可能发生。
切换到事务隔离级别更宽松的数据库,您应该能够看到一个OptimisticLockingException。
https://stackoverflow.com/questions/74464975
复制相似问题