kros365
kros365

Reputation: 105

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?

Upvotes: 4

Views: 3386

Answers (2)

Peter Lustig
Peter Lustig

Reputation: 1701

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 ...");
}

Upvotes: 1

Vesa Karjalainen
Vesa Karjalainen

Reputation: 1105

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

Upvotes: 1

Related Questions