The exact error:
"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')
My class has id
and non-id
field which is alphanumeric
and has 5 characters and unique and 2 characters prefix:
public class Holiday {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotNull
@Column(unique = true)
@Size(min = 7, max = 7)
private String reference;
}
i am setting this code
field in another service:
@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();
}
I set like this:
private final ReferenceGeneratorService referenceGeneratorService;
Holiday holiday = new Holiday();
holiday.setReference(referenceGeneratorService.generateReference(PREAPP));
The db is mysql
and we use spring boot.
When i send multiple requests at same time, for example from swagger
, it can give
DataIntegrityViolationException , the reference is already used
I tried lots of things.
I am open to any suggestions. The purpose is the field must be unique and alphanumeric.
I tried that for example:
String increment for alphanumeric field is for JPA not working
QQ is prefix