如何使用SimpleJdbcInsert和MapSqlParameterSource批量插入?

问题描述 投票:0回答:2

以下内容有效,但是如何收集多个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);
java spring spring-jdbc
2个回答
1
投票

幸运的是SimpleJdbcInsert可以采用MapSqlParameterSource的数组(而不是列表)。因此可能如下:

List<MapSqlParameterSource> entries = new ArrayList<>();
entries.add(entry);

MapSqlParameterSource[] array = entries.toArray(new MapSqlParameterSource[entries.size()]);
insert.executeBatch(array);

0
投票

[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));
© www.soinside.com 2019 - 2024. All rights reserved.