如何使用Sping JDBCTemplate获取HashMap中的'key'和'value'列数据



假设,我有一个如下表格-

Id | Key | Value
----------------
01 | one | 1_val
02 | two | 2_val

我希望两列 - 键和值 - 作为HashMap

使用Spring JDBC模板最合适的方法是什么?

你需要一些类似的东西:

        JdbcTemplate template = new JdbcTemplate(dataSource);
        ResultSetExtractor<HashMap<String, String>> rse = rs -> {
            HashMap<String, String>  retVal = new HashMap<>();
            while(rs.next()) {
                retVal.put(rs.getString("Key"), rs.getString("Value"));
            }
            return retVal;
        };
        HashMap<String, String> result = template.query("select Key, Value from Table", rse);

你为什么要把它作为HashMap

你可以有一个方法来为你创建那个对象

public Map<String, String> getTableAsMap() throws SQLException
{
    ResultSet rs = connection.createStatement().executeQuery("SELECT Key, Value FROM KeyValueTable;");
    Map<String, String> map = new HashMap<>();
    while (rs.next())
    {
        map.put(rs.getString(1), rs.getString(2));
    }
    return map;
}

编辑:这不是春天,但你应该明白这个想法。

相关内容

最新更新