Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data duplicate key value

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?

like image 811
kros365 Avatar asked Nov 04 '25 05:11

kros365


2 Answers

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

like image 142
Vesa Karjalainen Avatar answered Nov 06 '25 20:11

Vesa Karjalainen


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 ...");
}
like image 32
Peter Lustig Avatar answered Nov 06 '25 20:11

Peter Lustig