mybatis查询结果包含集合

2022-08-24 10:26:20

只需要在 xml中,把返回结果单独定义即可。

本质上就是一个关联查询,相当于group by 分组了一下,字段相同的那个,被提取出来到外边的那个对象里了。

1.表说明

本案例,两张表,多对一,本次案例,一个学生有多个课程

学生表:a表:id,name
课程表:b表:id,name,sId(外键学生id)

2. xml写法说明

<!-- mapper接口对应的sql查询语句--><selectid="getPage"resultMap="hasCollection"><!--
    	resultMap指定返回使用下边写的对象,正常写查询
		测试直接使用sql查询,会出现多个记录,学生,以及不同的课程名称,
		通过这个resultMap,会按学生进行分组,重复的字段(学生信息),会抽取出来,到第一层resultMap里
	-->
        SELECT
        a.id as id,
        a.`name` as `name`,
        b.id as lessonId,
        b.`name` as lessonName,
        b.sId
        FROM
        lesson AS b,
        student AS a
        where b.student_id = a.id</select><!-- 此处定义需要返回的对象--><!--
		column需要是sql句子中查到的字段的别名(没别名就是名字),
		property中,是指定映射到实体上的字段名,
		collection中:javatype是指定返回结果中的对象
	--><resultMapid="hasCollection"type="com.mbg.dto.StudentLessonDTO"><idcolumn="id"jdbcType="INTEGER"property="id"/><resultcolumn="name"jdbcType="VARCHAR"property="name"/><collectionproperty="lessons"resultMap="lessonCollection"/></resultMap><resultMapid="lessonCollection"type="com.mbg.entity.Lesson"><idcolumn="lessonId"jdbcType="INTEGER"property="id"/><resultcolumn="lessonName"jdbcType="VARCHAR"property="name"/><resultcolumn="sId"jdbcType="VARCHAR"property="sId"/></resultMap>

3. 实体类

用到了lombok

@DatapublicclassStudentLessonDTOextendsStudentimplementsSerializable{privateList<Lesson> lessons;}@DatapublicclassStudentimplementsSerializable{privateInteger id;privateString name;}@DatapublicclassLessonimplementsSerializable{privateInteger id;privateString name;privateInteger sId;}
  • 作者:叶梓啊
  • 原文链接:https://blog.csdn.net/weixin_43329956/article/details/123745080
    更新时间:2022-08-24 10:26:20