1

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

asdasasd
  • 81
  • 1
  • 9
  • 1
    The error suggests that the key generated or the unique column had a duplicate entry, did you try to debug and check if that is the case. – Syed Anas Nov 23 '18 at 10:01
  • @Anas i tried to send multiple requests to save, so because of this it happens.If i debug, i cant do it so fast. I send 10 15 requests in 10 seconds to save. So it cant lock database for it probably. – asdasasd Nov 23 '18 at 13:57
  • Assuming if you debug the 10 15 request and the issue doesn't arise, then it means its a concurrency issue and since spring boot works on threads for each request, can you try using any concurrent object? For example ConcurrentHashMap – Syed Anas Nov 26 '18 at 06:21

0 Answers0