public Long upsertCreditRiskInformation(@Valid CreditRiskInformationCodeTermBasedRequest request, Boolean codeBased)
throws IOException {
`CreditRisk creditRisk =` creditRiskDataRepository.findByOrganisationId(organisation.getId());
if (creditRisk == null) {
if (codeBased) {
creditRisk =
new CreditRisk(null, creditRiskData, null, getExternalQueryDate(creditRiskData), organisation);
} else {
creditRisk =
new CreditRisk(creditRiskData, null, getExternalQueryDate(creditRiskData), null, organisation);
}
} else {// modify
creditRisk.modifyCreditRisk(creditRisk, request.getCreditRiskData(), getExternalQueryDate(creditRiskData),
codeBased);
}
return creditRiskDataRepository.save(creditRisk).getId();
}
}
这是同时从2个地方调用的方法。
一个发送给codebased=true
,另一个发送给false
。因此,如果是新创建的,则两者都可以尝试创建新的。
我该如何预防?
我使用了@Transactional(isolation = Isolation.READ_COMMITTED)
方法的顶部。但是这次,错误是:
ould not execute statement; SQL [n/a]; constraint [UK_jvmwr3y956lfnbk4fhh859cof]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement (Duplicate entry '13' for key 'UK_jvmwr3y956lfnbk4fhh859cof')
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [UK_jvmwr3y956lfnbk4fhh859cof]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
我不明白错误在哪里。它表示最后一行repository.save
因为我之前做过null check
,所以lock
并没有阻止它。因为null检查在锁定之前都显示为null。
我该怎么办?