Home > Software design >  Is there a way to insert a row in a father table with autoincrement primary key and a child table in
Is there a way to insert a row in a father table with autoincrement primary key and a child table in

Time:11-19

I don' t know how to insert a row in the child table that has an attribute that references to the column ID (primary key of the father Table)in the same transaction because i dont know the father primary key if i don't commit the transaction. Is there a way to solve this problem?

CodePudding user response:

You already answered your question: you don't have enough data before transaction's commit. Maybe try something like nested transactions? Note that not every database supports this feature.

CodePudding user response:

Mysql has LAST_INSERT_ID() function.

CodePudding user response:

When you have executed your statement, call getGeneratedKeys() to fetch the generated keys:

Statement statement =
    connection.prepareStatement("insert into ..",
                                Statement.RETURN_GENERATED_KEYS);
statement.executeUpdate();
ResultSet keys = statement.getGeneratedKeys();
...
  • Related