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?
-
1Can you share the way you generate id?Uladzislau Kaminski– Uladzislau Kaminski2020-03-03 18:56:26 +00:00Commented Mar 3, 2020 at 18:56
-
this problem is not related to id, another field msut be unique.kros365– kros3652020-03-03 18:59:35 +00:00Commented 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?InsertKnowledge– InsertKnowledge2020-03-03 19:09:11 +00:00Commented 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?kros365– kros3652020-03-03 19:14:56 +00:00Commented Mar 3, 2020 at 19:14
Add a comment
|
2 Answers
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
Manoj
If you use dataIntegrityViolationexception that would lead to suppressing other db exceptions as well and not just duplicatekey exception