0
public List<ColorModel> getAllColor() {
  String query = "SELECT * FROM COLOR";
  List<ColorModel> colors = getjdbcTemplate().query(query, new ColorMapper());
  return colors;
}

class ColorMapper implements RowMapper<Color> {
  public ColorModel mapRow(ResultSet rs, int rowNum) throws SQLException {
    ColorModel color = new ColorModel ();
    color.setId(rs.getInt("ID"));
    color.setName(rs.getString("color_name"));
  }
}

问题

我怎么能宁愿返回LinkedHashMap<Integer, String>而不是List<ColorModel>

4

2 回答 2

3

好吧,在将结果作为列表获取后,您可以轻松地执行映射:

...
List<Color> colors = getjdbcTemplate().query(query, new ColorMapper());
Map<Integer, String> colorMap = new LinkedHashMap<Integer, String>();
for (Color color : colors) {
    colorMap.put(color.getId(), color.getName());
}
return colorMap;

或者,您可以提供RowCallbackHandler

final Map<Integer, String> colorMap = new LinkedHashMap<Integer, String>();
getJdbcTemplate().query(query, new RowCallbackHandler() {
    @Override
    public void processRow(ResultSet rs) {
        colorMap.put(rs.getInt("ID"), rs.getString("color_name"));
    }
});

请注意,您不能Map<int, String>在 Java 中创建 a,因为泛型类型参数不能是原始类型。

于 2013-05-15T19:11:57.730 回答
0
public List<ColorModel> getAllColor() {
Map<Integer,String> map = LinkedHashMap<Integer, String>();    
  String query = "SELECT * FROM COLOR";
  List<Color> colors = getjdbcTemplate().query(query, new ColorMapper());
  for (Color color : colors) {
    colorMap.put(color.getId(), color.getName());
}
return map;
}
于 2013-05-15T19:12:52.360 回答