sample
public <T> void batchInsertMultiValues(
JdbcTemplate jdbcTemplate,
String baseSql, // "INSERT INTO MY_TABLE (A,B,C) VALUES "
List<T> list,
int batchSize,
BiConsumer<PreparedStatement, T> setter) throws SQLException {
int total = list.size();
for (int i = 0; i < total; i += batchSize) {
int end = Math.min(i + batchSize, total);
List<T> batch = list.subList(i, end);
// VALUES (?, ?, ?), (?, ?, ?), ...
StringBuilder sqlBuilder = new StringBuilder(baseSql);
for (int j = 0; j < batch.size(); j++) {
sqlBuilder.append("(?, ?, ?)");
if (j < batch.size() - 1) sqlBuilder.append(",");
}
String sql = sqlBuilder.toString();
jdbcTemplate.execute((ConnectionCallback<Void>) conn -> {
try (PreparedStatement ps = conn.prepareStatement(sql)) {
int paramIndex = 1;
for (T item : batch) {
setter.accept(ps, item); // ⚠️ setter에서는 3개 세팅해야 함
paramIndex += 3;
}
ps.executeUpdate();
}
return null;
});
log.info("✅ Inserted batch {}~{} ({} rows)", i + 1, end, batch.size());
}
}
batchInsertMultiValues(
jdbcTemplate,
"INSERT INTO MY_TABLE (A,B,C) VALUES ",
dataList,
1000,
(ps, item) -> {
ps.setString(1, item.getA());
ps.setString(2, item.getB());
ps.setString(3, item.getC());
}
);