问题描述
我从数据库拿一些分类的数据,结果集是一个列表,下面是xml代码
<select id="getTimes" resultType="java.util.List">
SELECT COUNT(is_promise) AS appTimes,
SUM(CASE WHEN is_promise = 1 THEN 1 ELSE 0 END) AS comTimes,
SUM(CASE WHEN is_promise = 2 THEN 1 ELSE 0 END) AS breTimes
FROM `order`
WHERE user_id = #{id}
</select>
这里的resultType返回值写List的话,执行结果只能拿到第一个值,我没去深入了解为什么,但我不想去创建新的对象去映射,因此我在网上也搜了蛮久,最终找到解决方法
解决方法
把返回值写成HsahMap,Mybatis-Plus会自动把值映射成hashmap集合,hashmap的key就是字段名,hashmap的值就是查询结果。代码如下
xml代码
<select id="getTimes" resultType="HashMap">
SELECT COUNT(is_promise) AS appTimes,
SUM(CASE WHEN is_promise = 1 THEN 1 ELSE 0 END) AS comTimes,
SUM(CASE WHEN is_promise = 2 THEN 1 ELSE 0 END) AS breTimes
FROM `order`
WHERE user_id = #{id}
</select>
mapper代码
HashMap<String, Integer> getTimes(Integer id);
map结果
![](https://i-blog.csdnimg.cn/blog_migrate/cfe776ea0f6831ceea985ad7fb83ade2.png)
发现返回值和select语句的查询结果不一致,如果想要一致的话把resultType 的值写成java.util.LinkedHashMap,改了之后的返回值
![](https://i-blog.csdnimg.cn/blog_migrate/c7e5468e5e9e35550f73d9747c63d04f.png)