Search code examples
javasqlnetbeansderbyjavadb

Java DB How to Insert Values for Foreign Keys into Table Column


I am using java DB database and NetBeans 8.0 for a desktop application
I am also using a PreparedStatement to query the database.

below is the code for creating the tables.

CREATE TABLE ALUMNUS (
   ALUMNUA_ID INT NOT NULL PRIMARY KEY 
       GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), 
   FIRST_NAME VARCHAR (45),
   LAST_NAME VARCHAR (45),
   OTHER_NAME VARCHAR (100)
);

CREATE TABLE DUES (
   ID INT NOT NULL PRIMARY KEY 
       GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
   PAYMENT_YEAR DATE,
   AMOUNT DOUBLE,
   ALUMNUS_ID INT 
);

--FOREIGN KEY
ALTER TABLE APP.DUES 
   ADD FOREIGN KEY (ALUMNUS_ID) REFERENCES APP.ALUMNUS(ID);

Now I want to insert, delete and update the foreign key values in APP.DUES table. what is the best option; trigger , stored procedure or the preparedstatement?

An example will be good.


Solution

  • If you want to primarily insert into the DUES table, you would use a sub select in SQL. I havent tested it with Java DB, but it basically looks like:

    INSERT INTO DUES(PAYMENT_YEAR, AMOUNT,ALUMNUS_ID)
              VALUES(2014,         100.0,
                                     (SELECT ALUMNUA_ID from  ALUMNUS where ...));
    

    You need to catch the "not found" error case and prepend a INSERT (and need to catch the duplicate case for that as well).

    See also: Insert Data Into Tables Linked by Foreign Key