无法执行语句;对于唯一性DataIntegrityViolationException:

时间:2018-11-23 08:51:05

标签: hibernate spring-boot jpa

确切的错误:

"DataIntegrityViolationException : could not execute statement; SQL [n/a]; constraint [UCIDXNUFQCFS2J6QMVYBIXJFNORH8C]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement (Duplicate entry 'QQAB3GY' for key 'UCIDXNUFQCFS2J6QMVYBIXJFNORH8C')

我的班级有id的{​​{1}}和non-id字段,具有5个字符,唯一和2个字符的前缀:

alphanumeric

我正在另一项服务中设置此public class Holiday { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @NotNull @Column(unique = true) @Size(min = 7, max = 7) private String reference; } 字段:

code

我这样设置:

@Transactional(isolation = SERIALIZABLE)
@Override
public String generateReference(String productCode) {

    ReferenceGenerator referenceGenerator = referenceGeneratorRepository.findByMnemonic(productCode);

    if (referenceGenerator != null) {
        referenceGenerator.setValue(incrementReference(referenceGenerator.getValue()));
        referenceGeneratorRepository.save(referenceGenerator);
    } else {
        referenceGenerator = referenceGeneratorRepository.save(new ReferenceGenerator(PREAPP, START_VALUE_FOR_REFERENCE_CODE));
    }

    return PREFIX_OF_REFERENCE_CODE + referenceGenerator.getValue();
}

数据库为private final ReferenceGeneratorService referenceGeneratorService; Holiday holiday = new Holiday(); holiday.setReference(referenceGeneratorService.generateReference(PREAPP)); ,我们使用mysql

当我同时发送多个请求(例如来自spring boot.的请求时,它可以给出

  

DataIntegrityViolationException ,该引用已被使用

我尝试了很多事情。

我愿意接受任何建议。目的是该字段必须是唯一的并且是字母数字。

例如,我尝试过

String increment for alphanumeric field is for JPA not working

QQ是swagger

0 个答案:

没有答案