如何从jdbc模板查询中提取哈希图对象

时间:2018-07-06 12:16:38

标签: java spring spring-boot jdbc jdbctemplate

我正在尝试从JDBCTemplate查询中提取2个整数列表/数组。 我认为检索Map是最实用的。 查询是

Map<Integer, Integer> availabletime = jdbctemp.query("
Select a.hour, 
    s.duration from appointment as a inner join services as s on a.service_fid=s.id 
where date=? and guru_fid=? 
    ",date,guru_fid,//mapperlogic.class);

我需要a.hour和s.duration作为哈希图的键值对。我对这里的行映射器逻辑有些困惑。 Ive至今仅映射到对象,例如

public class RoleRowMapper implements RowMapper<Role> {

@Override
public Role mapRow(ResultSet row, int rowNum) throws SQLException {
    Role role=new Role();
    role.setId(row.getLong("id"));
    role.setName(row.getString("name"));
    return role;
}

} `有人可以帮助我将查询结果提取到地图或多个列表中吗?

1 个答案:

答案 0 :(得分:2)

我认为这应该适合您的情况。

  public Map<Integer,Integer> getAvailableTime(Date date, Integer guru_fid) {
                return jdbctemp.query("Select a.hour, s.duration from appointment as a inner join services as s on a.service_fid=s.id where date=? and guru_fid=? ",new Object[] { date, guru_fid }, (ResultSet rs) -> {
                HashMap<Integer,Integer> results = new HashMap<>();
                while (rs.next()) {
                    results.put(rs.getInt("a.hour"), rs.getInt("s.duration"));
                }
                return results;
            });

        }