4

I have a table in postgresql with unique constraint and after insert i can get the error duplicate key value violates unique constraint. How best way to skip this error (for example, ON CONFLICT DO NOTHING) using spring data?

4
  • 1
    Can you share the way you generate id? Commented Mar 3, 2020 at 18:56
  • this problem is not related to id, another field msut be unique. Commented Mar 3, 2020 at 18:59
  • What exactly do you want to achieve? Have the row inserted by undermining the constraint (impossible) or have java not throw an exception and continue with the method? Commented Mar 3, 2020 at 19:09
  • I can just check if there is such a value in the database and if there is not, then insert it, but can I do it in 1 request? Commented Mar 3, 2020 at 19:14

2 Answers 2

1

If you want to forget the row in case of conflict, just use INSERT ... ON CONFLICT (field) DO NOTHING.

Sign up to request clarification or add additional context in comments.

Comments

1

You can catch the DataIntegrityViolationException exception and handle it the way you want e.g.

try {
    repository.save(myEntity);
} catch(DataIntegrityViolationException e) {
    System.out.println("Entity already exists. Skipping ...");
}

1 Comment

If you use dataIntegrityViolationexception that would lead to suppressing other db exceptions as well and not just duplicatekey exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.