Reputation: 29
I am using Spring Data JPA in my project and plan to adopt the Optimistic Locking mechanism. But I have not seen Spring Data JPA can work with Optimistic Lock.
I have a concrete example and as far as I understand it is a situation where Serializable Isolation cannot cover when multiple transactions are being read and updated.
I'm using the Cockroach Database, which only supports Serializable Isolation. And here are two functions that I'm used to interacting with the Database:
@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;
}
Account entity
public AccountDto getAccount(UUID id) {
AccountEntity entity = this.accountRepository.findById(id).orElseThrow();
return new AccountDto(entity.getId(), entity.getStatus());
}
GET 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;
}
PUT API
In the image, I expect to throw an OptimisticLockException
.
But when User 1 updates the account, it still can update the account normally. Because in the updateAccount
method, it was found the latest version of the account. And it can't occur the OptimisticLockException
.
So under what scenario can it throw an OptimisticLockException?
Upvotes: 1
Views: 1249
Reputation: 81862
Optimistic locking takes effect when a transaction starts with seeing version A of some data and later on sees a different version A' of that data.
But as you state Cockroach DB uses the transaction isolation level serializable. This means for each transaction everything looks like there are no other transactions running at the same time. Therefore the scenario above can't happen.
Switch to a database with more lenient transaction isolation level and you should be able to see an OptimisticLockingException
.
Upvotes: 1