【问题标题】:Spring boot Jdbctemplate returns the output in specified formatSpring boot Jdbctemplate以指定格式返回输出
【发布时间】:2021-02-12 12:08:15
【问题描述】:

我正在为我的应用程序使用 Spring Boot。使用 jdbctemplate 运行 MySQL 查询。

query = "Select * from users";

List<Map<String, Object>> response = jdbcTemplate.queryForList(query);

当前输出:

[
        {
            "id": 1,
            "firstname": "Sam",
            "address": "US"
        },
        {
            "id": 2,
            "firstname": "Alex",
            "address": "US"
        }
]

我想使用 jdbctemplate 返回如下输出。 jdbctemplate中是否有任何方法可以返回如下输出?

预期输出:

[
        [
            "id"
            "firstname"
            "address"
        ],
        [
            1,
            "Sam",
            "US"
        ],
        [
            2,
            "Alex",
            "US"
        ]
]

【问题讨论】:

  • 试试这样的: List result = jdbcTemplate.queryForList(query).stream().map(row -> row.values().toArray()).collect( Collectors.toList());
  • 您的Current output 是对网络请求的响应正文吗?
  • @HopeyOne 是的,它是一个网络请求
  • @zatef jdbctemplate 中有没有现成的方法?
  • 看起来不存在这样的方法..... jdbctemplate 的方法列表在这里,并且它们都不会返回数组数组(根据您的要求)。 docs.spring.io/spring-framework/docs/current/javadoc-api/org/…

标签: java spring-boot spring-jdbc jdbctemplate


【解决方案1】:

您可以利用ResultSetExtractorResultSet 映射到所需的响应结构中。可以从ResultSet 的元数据中检索这些列:rs.getMetadata()

ResultSetExtractor<List<List<Object>>> resultSetExtractor = new ResultSetExtractor<>() {

    @Override
    public List<List<Object>> extractData(ResultSet rs) throws SQLException, DataAccessException {
        List<List<Object>> result = new ArrayList<>();
        List<Object> columnNames = new ArrayList<>();
        result.add(columnNames);

        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        for (int col = 1; col <= columnCount; col++) {
            String columnName = rsmd.getColumnName(col);
            columnNames.add(columnName);
        }

        while (rs.next()) {
            List<Object> row = new ArrayList<>();
            result.add(row);
            for (int col = 1; col <= columnCount; col++) {
                Object value = rs.getObject(col);
                row.add(value);
            }
        }
        return result;
    }
};
return jdbcTemplate.query("Select * from user", resultSetExtractor);

【讨论】:

    猜你喜欢
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 2018-10-16
    相关资源
    最近更新 更多