How to perform batch update in Spring with a list of maps?

前端 未结 4 1851
旧巷少年郎
旧巷少年郎 2021-01-04 06:51

New to Spring, I am trying to insert a List> into a table. Until now I have been using the SqlParameterSource for b

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 07:33

    There is another way to awoid @SuppressWarnings("unchecked").

    public static final String INSERT_INTO = "INSERT INTO {0} ({1}) VALUES ({2})";
    
    private NamedParameterJdbcTemplate template;
    
    
    template.batchUpdate(insertQuery(rowMaps.get(0)), batchArgs(mapRows));
    
    /**
     * Create SQL instruction INSERT from Map record
     *
     * @return literal INSERT INTO [schema].[prefix][table_name] (column1, column2, column3, ...)
     * VALUES (value1, value2, value3, ...);
     */
    public String insertQuery(Map rowMap) {
        String schemaTable = Objects.isNull(getSchema()) ? table : getSchema() + "." + table;
        String splittedColumns = String.join(",", rowMap.keySet());
        String splittedValues = rowMap.keySet().stream()
                .map(s -> ":" + s).collect(Collectors.joining(","));
        return MessageFormat.format(INSERT_INTO, schemaTable, splittedColumns, splittedValues);
    }
    
    private MapSqlParameterSource[] batchArgs(List> mapRows) {
        int size = mapRows.size();
        MapSqlParameterSource[] batchArgs = new MapSqlParameterSource[size];
        IntStream.range(0, size).forEach(i -> {
            MapSqlParameterSource args = new MapSqlParameterSource(mapRows.get(i));
            batchArgs[i] = args;
        });
    
        return batchArgs;
    }
    

    Best regards

提交回复
热议问题