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>
答案 0 :(得分: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"));
}
});
请注意,您无法在Java中创建Map<int, String>
,因为泛型类型参数不能是基本类型。
答案 1 :(得分: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;
}