When i try to save via swagger
,It gives those errors:
INTERNAL_SERVER_ERROR(PERSISTENCE_DATAACCESS_EXCEPTION) - DataIntegrityViolationException : could not execute statement; SQL [n/a]; constraint [UK_8q03as5by8j5kvtroc1dyl0lo]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute
My class is this:
public class Book{
@Id
private long id;
@NotNull
@Column(unique = true)
@Size(min = 7, max = 7)
private String referenceCode;;//this field makes the error because of not unique value creation
That referenceCode
is also unique. I am keeping the value in another table. And it has another service to save and increment:
@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 String incrementReference(String value) {
return Long.toString( Long.parseLong(value, 36) + 1, 36).toUpperCase();
}
}
In my main service, while saving, it uses this:
public class Bookservice{
public void createBook(){
book.setReferenceCode(referenceGeneratorService.generateReference("BOOK));
BookApplication savedBook = bookRepository.save(book);
On swagger
, when i sent lots of requests to save, it can sometimes fail to save. Because of duplication and uniqueness. Concurrency
How can i prevent this?
Lock or something? I dont want to lose data also.
I can use pessimist lock but maybe there are other ways? Also i can change the method that makes it unique but i want to keep it.
Like this https://stackoverflow.com/a/53259441/10309977
i put synchronized
to the method but i can again get the errors.
@Override
public synchronized String generateReference(String productCode) {
I put here.
Maybe i should put to BookService.java
class?