users@glassfish.java.net

How to simulate JPA's "strategy=TABLE" PK generation using JDBC?

From: Witold Szczerba <pljosh.mail_at_gmail.com>
Date: Tue, 9 Oct 2007 01:03:15 +0200

Hi there,
in my application, I use Toplink Essentials' JPA implementation with
Glassfis v2 server.
Application is almost finished, but I encountered problem with batch
inserting records into database - TopLink is not good with that
because it does not implement em.getReferece(...), it does exactly the
same thing what em.find(...).

I have to insert large amount of Transaction entities into database -
20000 or more and each transaction requires Loan entity. If I would
invoke em.find(...) for each Loan - the operation would last for ever
and it would eat entire memory, so I have to do it using plain JDBC
(stmt.addBatch() and stmt.executeBatch()).

The problem is with ID generation - my application uses default
TopLink strategy - there is a SEQUENCE table with SEQ_NAME and
SEQ_COUNT columns.

How am I suppose to use it not to get in conflict with what TopLink
does? This application is used by a large amount of users in the same
time and I do not want to brake anything by incorrect use of SEQUENCE
table.

I was thinking: maybe I should, just before inserting those 20000
entities, read the SEQ_COUNT column, remember the value and update it
with its old value + the number of entities I want to add - all this
in a separate transaction just before inserting... But what If my
transaction would fail? I would have to throw into the trash all 20000
PKs (they would be useless)... So, maybe I can SELECT FOR UPDATE that
SEQUENCE table and increment it in the same transaction with my
entities insertion, but what if in the mean time TopLink would run out
of available PKs and would like to fetch more? Would TopLink just wait
for my transaction to finish or every JPA insert into database would
cause exception?

What are your suggestions?

Best regards,
Witold Szczerba