【发布时间】:2020-06-06 21:56:50
【问题描述】:
我正在使用jdbcTemplate 批量插入到 2 个表中。第一张桌子很简单,有一个ID。第二个表有一个 FK 参考 USER_ID,我需要在插入之前从表 1 中获取它。
假设我有这个:
主要 Java 代码(这里我分成多个批次
for(int i = 0; i < totalEntries.size(); i++) {
// Add to Batch-Insert List; if list size ready for batch-insert, or if at the end, batch-persist & clear list
batchInsert.add(user);
if (batchInsert.size() == 1000 || i == totalEntries.size() - 1) {
// 1. Batch is ready, insert into Table 1
nativeBatchInsertUsers(jdbcTemplate, batchInsert);
// 2. Batch is ready, insert into Table 2
nativeBatchInsertStudyParticipants(jdbcTemplate, batchInsert);
// Reset list
batchInsert.clear();
}
}
批量插入表 1 的方法(注意,我在这里为 USERS_T 获取 Seq Val)
private void nativeBatchInsertUsers(JdbcTemplate jdbcTemplate, final List<UsersT> batchInsert) {
String sqlInsert_USERS_T = "INSERT INTO PUBLIC.USERS_T (id, password, user_name) " +
"VALUES (nextval('users_t_id_seq'), ?, ? " +
")";
// Insert into USERS_T using overridden JdbcTemplate's Native-SQL batchUpdate() on the string "sqlInsert_USERS_T"
jdbcTemplate.batchUpdate(sqlInsert_USERS_T, new BatchPreparedStatementSetter() {
@Override
public int getBatchSize() {
return batchInsert.size();
}
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1, null);
ps.setString(2, batchInsert.get(i).getUsername());
// etc.
});
}
批量插入表2的方法
private void nativeBatchInsertStudyParticipants(JdbcTemplate jdbcTemplate, final List<UsersT> batchInsertUsers) {
String sqlInsert_STUDY_PARTICIPANTS_T =
"INSERT INTO PUBLIC.STUDY_PARTICIPANTS_T (id, study_id, subject_id, user_id) "
"VALUES (nextval('study_participants_t_id_seq'), ?, ?, ?
")";
// Insert into STUDY_PARTICIPANTS_T using overridden JdbcTemplate's Native-SQL batchUpdate() on the string "sqlInsert_USERS_T"
jdbcTemplate.batchUpdate(sqlInsert_STUDY_PARTICIPANTS_T, new BatchPreparedStatementSetter() {
@Override
public int getBatchSize() {
return batchInsert.size();
}
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
// PROBLEM: For Param #4, USER_ID, need to get the USERS_T.ID from Batch-Insert #1
}
});
}
当我来到第二批插入时,其中一列是返回到 USERS_T.ID 的 FK,称为 STUDY_PARTICIPANTS_T.USER_ID。我是否可以通过保持jdbcTemplate.batchUpdate() 逻辑来获得它?
【问题讨论】:
标签: java spring spring-jdbc jdbctemplate batch-insert