以下内容有效,但是如何收集多个MapSqlParameterSource
并将它们全部插入一批?
new SimpleJdbcInsert(ds).withTableName(TABLENAME);
MapSqlParameterSource entry = new MapSqlParameterSource()
.addValue("id", report.queryId, Types.INTEGER)
.addValue("firstname", report.reportDate, Types.DATE)
.addValue("age", report.completionRatio, Types.INTEGER);
insert.execute(entry);
幸运的是SimpleJdbcInsert
可以采用MapSqlParameterSource
的数组(而不是列表)。因此可能如下:
List<MapSqlParameterSource> entries = new ArrayList<>();
entries.add(entry);
MapSqlParameterSource[] array = entries.toArray(new MapSqlParameterSource[entries.size()]);
insert.executeBatch(array);
[SqlParameterSourceUtils
还有一种更好的方法
private final List<Map<String, Object>> records = new LinkedList<>();
final SimpleJdbcInsert statement = new SimpleJdbcInsert(dataSource)
.withTableName("stats")
.usingGeneratedKeyColumns("id")
.usingColumns("document", "error", "run", "celex");
statement.executeBatch(SqlParameterSourceUtils.createBatch(records));