Spring boot Jdbctemplate 返回指定格式的输出

Gal*_*let 2 java spring-jdbc jdbctemplate spring-boot

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

query = "Select * from users";

List<Map<String, Object>> response = jdbcTemplate.queryForList(query);
Run Code Online (Sandbox Code Playgroud)

电流输出:

[
        {
            "id": 1,
            "firstname": "Sam",
            "address": "US"
        },
        {
            "id": 2,
            "firstname": "Alex",
            "address": "US"
        }
]
Run Code Online (Sandbox Code Playgroud)

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

预期输出:

[
        [
            "id"
            "firstname"
            "address"
        ],
        [
            1,
            "Sam",
            "US"
        ],
        [
            2,
            "Alex",
            "US"
        ]
]
Run Code Online (Sandbox Code Playgroud)

man*_*uti 5

您可以利用 将ResultSetExtractor映射ResultSet到所需的响应结构中。可以从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);
Run Code Online (Sandbox Code Playgroud)