mybatis分组查询 返回map一个值做可以,另一个值做value
时间: 2024-01-23 16:03:46 浏览: 210
可以使用MyBatis的resultMap来实现这个需求。具体步骤如下:
1. 在mapper.xml中编写SQL语句,使用GROUP BY对数据进行分组,并使用聚合函数计算需要的值。例如:
```
SELECT category, COUNT(*) AS count FROM products GROUP BY category
```
2. 在mapper.xml中定义resultMap,将查询结果映射到一个Map对象中。例如:
```
<resultMap id="categoryCountMap" type="java.util.HashMap">
<result column="category" property="key"/>
<result column="count" property="value"/>
</resultMap>
```
3. 在mapper.xml中使用resultMap,将查询结果转换为Map对象。例如:
```
<select id="getCategoryCount" resultMap="categoryCountMap">
SELECT category, COUNT(*) AS count FROM products GROUP BY category
</select>
```
4. 在Java代码中调用mapper方法,获取Map对象。例如:
```
Map<String, Integer> categoryCountMap = mapper.getCategoryCount();
```
其中,Map的key为分组的字段值,value为聚合函数计算的结果值。
阅读全文
相关推荐


















