skip to Main Content

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?

3

Answers


  1. 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.

    Login or Signup to reply.
  2. Mysql has LAST_INSERT_ID() function.

    Login or Signup to reply.
  3. 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();
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search