auto-incrementhsqldbembedded-database

How to get the generated ID of an auto increment column after insertion of a record in HSQLDB within same connection?


I have created a table as

    create table test(log_id integer identity primary_key, filename varchar, filecontent blob)

Now my query in java inserts values in test using prepared statement as

    insert into test(filename, filecontent) values (?,?);

After insertion I want to know what is the log_id of this latest inserted record while being in same db connection because; based on this log_ID I want to insert another child record with same log_id as foreign key in another table? I checked the call identity() method but i don't know how to use it in java code and get the returned value? please help


Solution

  • You can use the identity() method in the next INSERT statement for the child table. In this example the child table has a ref_id column for the foreign key plus a data_col for its data. The child table has its own primary key column and a foreign key column that references the log_id column of the test table.

    create table child(child_id integer identity primary_key, ref_id integer, data_col varchar);
    alter table child add constraint child_fk foreign key (ref_id) references test(log_id);
    insert into child(ref_id, data_col) values (identity(), ?);