I have a table with unique constraint on 2 columns (user1 and user2), so that there cannot be any duplicated pair of users. It looks like this:
@Table(name = "relation", uniqueConstraints ={ @UniqueConstraint(columnNames = { "user1", "user2" }) }) class Relation{} ... Columns user1 and user2 are uuid-char's
When I receive data from some remote end, I get a list of pairs which I have to insert to my table. This is the list I receive:
{ user1: some-uuid, user2: some-other-uuid } { user1: some-uuid, user2: some-other-uuid } { user1: some-uuid, user2: some-other-uuid } ... + 1000 records Then, I iterate over that list and insert all the pairs:
for(Pair p : data){ try{ relationRepository.save(p); } catch(PostgresConstraintViolationException ex){ log("Pair already exists, but that's ok") } } My question is:
Does intentionally catching ConstraintViolationException have any performance impact? It seems much more better, than checking if the pairs exist in the database and insert if it doestn't. (1 query instead of 2).
I once heard that "This is what exceptions are for". I understand that, but I'm not sure how Postgres behaves in this situation.