只需要在 xml中,把返回结果单独定义即可。
本质上就是一个关联查询,然后把关联表的字段抽取到指定对象中了。
1.表说明
本案例,两张表,多对一,本次案例,一个课程下,只有一个学生的信息
学生表:a表:id,name
课程表:b表:id,name,sId(外键学生id)
2. xml写法说明
<!-- mapper接口对应的sql查询语句-->
<select id="getPage" resultMap="hasPOJO">
<!--resultMap指定返回使用下边写的对象,正常写查询,会把查询到的字段,根据返回对象的定义,抽取到对象的字段里-->
SELECT
a.id as id,
a.`name` as `name`,
b.id as lessonId,
b.`name` as lessonName,
b.sId as sId
FROM
lesson AS b,
student AS a
where b.student_id = a.id
</select>
<!-- 此处定义需要返回的对象-->
<!--
column需要是sql句子中查到的字段的别名(没别名就是名字),
property中,是指定映射到实体上的字段名,
association中:javatype是指定返回结果中的对象
-->
<resultMap id="hasPOJO" type="com.mbg.dto.LessonDTO">
<id column="lessonId" jdbcType="INTEGER" property="id"/>
<result column="lessonName" jdbcType="VARCHAR" property="name"/>
<result column="sId" jdbcType="INTEGER" property="sId"/>
<association property="student" javaType="com.mbg.entity.Student">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
</association>
</resultMap>
3. 实体类
用到了lombok
@Data
public class LessonDTO extends Lesson implements Serializable {
private Student student;
}
@Data
public class Student implements Serializable {
private Integer id;
private String name;
}
@Data
public class Lesson implements Serializable {
private Integer id;
private String name;
private Integer sId;
}