简体   繁体   中英

Select and Create_If_Not_Available versus Create always on a table with Unique Constraint

Please deal with this basic question.

I have a table T with unique constraint on composite columns "A" and "B".

While creating entry into T, I have two options:

1. Select and Create_If_Not_Available

a. Select * from T where A='a' and B='b'. b. If no entry available, create a new entry (with handling of ConstraintViolation because of race condition), else move to next step.

2. Create always

a. Create entry into DB (With handling of ConstraintViolation and relying on Databases's unique constraint).

As per me, 2nd will have less queries being fired on DB and replies on database (outside the application code).

First makes a lot of unnecessary calls but has very little dependency on unique constraint of database.

Given high scale, which one should I prefer and why?

I am using Java, Hibernate and Oracle.

Thanks,

The things done by the database in step 2 will have to be done in step 1 anyway, so from a pure efficiency standpoint, step 2 is better. Why do you care about "dependency on unique constraints"? From an integrity perspective, you need them.

If your application is attempting to insert a lot of records for existing keys, it seems to me you have other problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM