views:

67

answers:

1

Hello,

I have an table (in ORADB) containing two columns: VARCHAR unique key and NUMBER unique key generated from an sequence.

I need my Java code to constantly (and in parallel) add records to this column whenever a new VARCHAR key it gets, returning the newly generated NUMBER key. Or returns the existing NUMBER key when it gets an existing VARCHAR (it doesn't insert it then, that would throw an exception of course due to the uniq key violation).

Such procedure would be executed from many (Java) clients working in parallel.

Hope my English is understandable :)

What is the best (maybe using PL/SQL block instead of Java code...) way to do it?

+2  A: 

I do not think you can do better than

  1. SELECT the_number FROM the_table where the_key = :key

  2. if found, return it

  3. if not found, INSERT INTO the_table SELECT :key, the_seq.NEXT_VAL RETURNING the_number INTO :number and COMMIT

  4. this could raise a ORA-00001(duplicate primary key insert) if the timing is unlucky. In this case, SELECT again.

Not sure if JDBC supports RETURNING, so you might need to wrap it into a stored procedure (also saves database roundtrips).

You can use an index-organized table (with the_key as primary key), makes the lookup faster.

Thilo