Java PreparedStatement带外键的多批插入
我有一个Java应用程序,正在尝试对MySQL数据库进行一系列批插入。但是,我的许多表都是通过外键链接的。所以我不知道要使用的外键的值,因为它们是在前一批中生成的Java PreparedStatement带外键的多批插入,java,mysql,prepared-statement,Java,Mysql,Prepared Statement,我有一个Java应用程序,正在尝试对MySQL数据库进行一系列批插入。但是,我的许多表都是通过外键链接的。所以我不知道要使用的外键的值,因为它们是在前一批中生成的 例如,以这两个表为例: 家长 id 名字 儿童 id 父项id(父项id所需的外键) 名字 我知道如何在不使用批次的情况下导入这些内容: //already initialized variables: Connection connection, List<ParentObject> parentObjects R
例如,以这两个表为例:
家长
id
名字 儿童
id
父项id(父项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();
}
}
我所使用的实际数据结构比上面的要复杂得多,但它说明了基本问题。我将如何使用批处理执行上述操作?我遇到的问题是,如果不知道要使用的父\u id外键,就无法插入子对象
我在别处寻找答案,但我找不到任何解决办法。我读了一些关于使用存储过程的书(如果可能的话,我希望避免使用存储过程)。效率在这里很重要,因为我正在处理可能数以百万计的记录。我很感激任何人的洞察力。不要认为使用生成的主键是可能的。如果您的应用程序只是数据库的一个客户端,那么您可以自己计算主键,并在准备好的语句中直接传递它们。在
executeBatch
之后,您可以获得生成的键,请参阅。因此,首先在批中插入父记录,获取父记录ID,然后在批中插入子记录。
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();