MyBatis selectMap方法返回结果不符合预期,如何获取以Code为键、Value为值的HashMap?
解决MyBatis selectMap返回嵌套Map的问题
嘿,我来帮你搞定这个问题!你现在得到的是嵌套Map结构,核心原因是MyBatis把每一行查询结果都封装成了一个HashMap(对应你设置的resultType="java.util.HashMap"),然后用Code作为外层Map的键,这个嵌套HashMap作为值。要得到你期望的扁平Map,有几种简单的解决方法:
方法1:直接返回单一值(最简单)
修改你的Mapper映射语句,让resultType为String,只查询Value列,然后在调用selectMap时指定Code作为键列:
<select id="getResults" resultType="java.lang.String"> select "Value" from "CodeValue" </select>
对应的Java代码无需改动,selectMap会自动把Code作为键,查询到的Value作为值:
Map<String, String> codeValueMap = getSqlSession().selectMap("getResults", null, "Code");
方法2:利用POJO和selectMap的重载方法(更面向对象)
如果你的MyBatis版本在3.4.0及以上,可以使用selectMap的四参数重载方法,直接指定键列和值对应的POJO属性:
首先修改Mapper语句,把resultType改成你的CodeValue类,同时用别名统一数据库列名和POJO属性名的大小写:
<select id="getResults" resultType="com.yourpackage.CodeValue"> select "Code" as code, "Value" as value from "CodeValue" </select>
然后调用四参数的selectMap,指定键是Code列,值是POJO的value属性:
Map<String, String> codeValueMap = getSqlSession().selectMap("getResults", null, "Code", "value");
方法3:手动转换嵌套Map(兼容旧版本)
如果你的MyBatis版本不支持四参数重载,可以先获取嵌套Map,再手动转换成你需要的扁平结构:
// 先获取嵌套Map Map<String, Map<String, String>> tempMap = getSqlSession().selectMap("getResults", null, "Code"); // 转换为扁平Map Map<String, String> codeValueMap = new HashMap<>(); for (Map.Entry<String, Map<String, String>> entry : tempMap.entrySet()) { codeValueMap.put(entry.getKey(), entry.getValue().get("Value")); }
这样就能得到你期望的{CODE1=A, CODE2=B,...}结构啦!
内容的提问来源于stack exchange,提问作者rajani chowdhary
相关产品推荐
相关产品推荐

