You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 05:02:49