简体   繁体   English

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

[英]How to batch insert with SimpleJdbcInsert and MapSqlParameterSource?

The followings works, but how can I collect multiple MapSqlParameterSource and insert them all in one batch?以下方法有效,但如何收集多个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);

Luckily SimpleJdbcInsert can take an array (not a list) of MapSqlParameterSource .幸运的是SimpleJdbcInsert可以采用MapSqlParameterSource的数组(不是列表)。 So it's possible as follows:所以有可能如下:

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

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

There is a better way of doing it with SqlParameterSourceUtils使用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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM