Java PreparedStatement使用外键进行多个批量插入

时间:2015-04-04 20:52:44

标签: java mysql prepared-statement

我有一个Java应用程序,我正在尝试对MySQL数据库进行一系列批量插入。但是,我的许多表都是通过外键链接的。所以我不知道要使用的外键的值,因为它们是在前一批中生成的。


例如,取这两个表:

ID
名字

儿童
ID
parent_id (parent.id所需的外键)
名字


我知道如何在不使用批次的情况下导入这些:

//already initialized variables: Connection connection, List<ParentObject> parentObjects

ResultSet rs = null;
PreparedStatement psParent = null;
PreparedStatement psChild = null;
for(ParentObject parent: parentObjects){
    psParent = connection.prepareStatement("INSERT INTO product (name) VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS);
    psParent.setString(1, parent.getName());
    psParent.executeUpdate();

    int parentId = 0;
    rs = psParent.getGeneratedKeys();
    if (rs.next())
        parentId = rs.getInt(1);

    rs.close();
    psParent.close();

    for(ChildObject child : parent.getChildren()){
        psChild = connection.prepareStatement("INSERT INTO child (parent_id, name) VALUES (?,?)");
        psChild.setInt(1, parentId);
        psChild.setString(2, child.getName());
        psChild.executeUpdate();
        psChild.close();
    }
}

现在我正在尝试使用批次:

PreparedStatement psParent = connection.prepareStatement("INSERT INTO product (name) VALUES (?)");
PreparedStatement psChild = connection.prepareStatement("INSERT INTO child (parent_id, name) VALUES (?,?)");
for(ParentObject parent: parentObjects){
    psParent.setString(1, parent.getName());
    psParent.addBatch();

    for(ChildObject child : parent.getChildren()){
        psChild.setInt(1, I_DONT_KNOW_HOW_TO_GET_THIS_ID_WHICH_HASNT_BEEN_INSERTED_YET);
        psChild.setString(2, parent.getName());
        psChild.addBatch();
    }
}

psParent.executeBatch();
psParent.close();
psChild.executeBatch();
psChild.close();

我使用的实际数据结构比上面的内容复杂得多,但它说明了基本问题。我如何使用批次执行上述操作?我遇到的问题是,在没有首先知道要使用的parent_id外键的情况下,无法插入子对象。

我在别处寻找答案,我找不到任何解决方法。我读了一些关于使用存储过程的内容(如果可能的话,我想避免使用它)。效率在这里非常重要,因为我正在处理数百万条记录。我很欣赏任何人可能有的见解。

1 个答案:

答案 0 :(得分:0)

不要认为生成的主键是可能的。如果您的应用程序只是数据库的一个客户端,那么您可以自己计算主键并直接在预准备语句中传递它们。