关于mybatis返回map集合的操作:
1.mapper.xml中写一个查询返回map的sql
<select id="findMap" parameterType="com.sxd.swapping.domain.HuaYangArea" resultType="java.util.HashMap"> select hy.uid, hy.area_name from hua_yang_area AS hy <where> <if test="areaPerson != null"> AND hy.area_person >= #{areaPerson} </if> </where> </select>
2.mapper.java 对应接收,注意,这里并不是直接使用Map<>接收,因为sql查出的不是一条数据,而是多条数据,所以是List<Map<>>接收
/** * mybatis 查询接收map集合 * @param area * @return */ List<Map<String,String>> findMap(HuaYangArea area);
3.错误写法:
错误的写法就是直接读取List中的Map<>
@Override public Map<String, String> findMap(HuaYangArea entity) { List<Map<String,String>> list = huaYangAreaMapper.findMap(entity); Map<String,String> res = new HashMap<>(); for (Map<String, String> stringStringMap : list) { System.out.println(stringStringMap.toString()); stringStringMap.forEach((k,v)->{ System.out.println("key:"+k+">>>value:"+v); res.put(k,v); }); } return res; }
这样查询到的结果是:
我们需要看一哈实际List<Map<>>中到底存储的是什么
结果集中存储是按照{字段名1:字段值1,字段名2:字段值2}
而我们其实期望的是{字段值1:字段值2}
4.正确写法:
所以正确的写法应该是
@Override public Map<String, String> findMap(HuaYangArea entity) { List<Map<String,String>> list = huaYangAreaMapper.findMap(entity); Map<String,String> res = new HashMap<>(); for (Map<String, String> stringStringMap : list) { System.out.println(stringStringMap.toString()); String uid = null; String areaName = null; for (Map.Entry<String,String> entry:stringStringMap.entrySet()){ if ("uid".equals(entry.getKey())){ uid = entry.getValue(); }else { areaName = entry.getValue(); } } res.put(uid,areaName); } return res; }
返回结果: