前言
一、多对一嵌套结果查询。
实体类:
@Data
public class Student {
private int id;
private String name;
private int tid;
//多对一
private Teacher teacher;
}
StudentMapper接口:
List<Student> getStudentAndTeacher(@Param("id") int id);
StudentMapper.xml:
<!--嵌套结果查询-->
<select id="getStudentAndTeacher" resultMap="getStudentTeacher">
SELECT s.id sid,s.name sname,t.id tid,t.name tname FROM student s,tearcher t WHERE s.`tid`= #{id}
</select>
<resultMap id="getStudentTeacher" type="com.zhy.entity.Student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" column="tid">
<id property="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</resultMap>
二、一对多嵌套结果查询。
实体类:
@Data
public class Teacher {
private int id;
private String name;
//一对多
private List<Student> students;
}
TeacherMapper接口:
Teacher getTeacherAndStudent();
TeacherMapper.xml:
<!--嵌套结果查询-->
<select id="getTeacherAndStudent" resultMap="getTeacherStudent">
SELECT t.`id` tid,t.`name` tname,s.`id` sid,s.`name` sname FROM tearcher t,student s WHERE t.`id`=s.`tid`
</select>
<resultMap id="getTeacherStudent" type="com.zhy.entity.Teacher">
<id property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="com.zhy.entity.Student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
<association property="teacher" column="tid">
<id property="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</collection>
</resultMap>
三、注意。
- 多对一使用association关联,一对多使用collection集合。
- javaType指实体类中属性的类型,ofType指泛型类型。