总所周知,数据库表查询的结果集映射到java中有两种类型可以对应一张表,一种是一个类对应一张,一种是一个map集合对应一张表的映射,一条数据就等同于一个map
第一种方式:自定义结果集的映射到map中
简单来说就是表中的字段对应map中的健,字段对应的值对应map中键对应的值
需求:统计每个年龄段的人数总和
dao接口方法
List<Map> testGroup();
sql语句
<resultMap id="myId2" type="map">
<result column="age" property="age"></result>
<result column="count(1)" property="num"></result>
</resultMap>
<select id="testGroup" resultMap="myId2">
select age,count(1) from t_user group by age
</select>
第二种方式:使用collection一对多的映射关系
正常mysql执行出来的结果集是这样的(此时并没有进行分组)
select id,age from t_user
使用一对多映射关系collection进行映射,进而达到分组效果
一:分组类别,我这里是按年龄进行分组
多:每个分组里面的数据,我这里每个年龄段的人
结果集映射的类
@Data
public class MonthQuestion {
private Integer age;
private List<String> ids;
}
Dao层的方法
List<MonthQuestion> getMothDayDoExamQuestionValue();
Mapper层的sql语句
<!-- mybatis一对多实现分组查询-->
<resultMap id="myId" type="MonthQuestion">
<id property="age" column="age"></id>
<collection property="ids" ofType="string" javaType="ArrayList">
<result column="id"></result>
</collection>
</resultMap>
<select id="getMothDayDoExamQuestionValue" resultMap="myId">
select id,age from t_user
</select>
分组后的结果集
以上两种方式均可实现分组,我个人推荐使用第一种方式,因为第二种方式每次都要专门定义一个类与之映射,较为麻烦