实体类:
Student

public class Student {
    private int id;
    private String name;
    private int tid;
    private Teacher teacher;
}

Teacher

public class Teacher {
    private int tid;
    private String tname;
    private List<Student> students;
}

方式一:

按结果嵌套查询(关联查询)

    <!--按结果嵌套查询-->
    <select id="getTeacher" resultMap="teacherStudent">
        select t.tid tid,t.tname tname,s.id sid,s.name sname  from
         teacher t,student s
         where s.tid = t.tid and t.tid =#{tid};
    </select>
    <resultMap id="teacherStudent" type="teacher">
        <!-- property实体类属性名  column数据库字段名 -->
        <result property="tid" column="tid"/>
        <result property="tname" column="tname"/>
        <!--复杂的属性,我们需要单独处理对象:
        association 集合: collection
        javaType=""指定属性的类型!
        集合中的泛型信息,我们使ofType获取 -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

详解:

image.png
实体类属性为集合,这里要使用collection

image.png
实体类中集合的泛型,使用ofType获取,即ofType="Student"


ofType与javaType区别:

javaType使用场景:
指定属性的类型
例如:
image.png
即javaType="Teacher"



ofType使用场景:
集合中的泛型信息,使用ofType获取
image.png
实体类中集合的泛型,使用ofType获取,即ofType="Student"


方式二:

按照查询嵌套处理(子查询)

(先查询老师信息,再查询学生信息)

    <!--=====方式二:按照查询嵌套处理=========-->
    <select id="getTeacherss" resultMap="teacherAndStudent">
        select * from teacher where tid = #{tid};
    </select>
    <resultMap id="teacherAndStudent" type="teacher">
         <collection property="students" ofType="Student" javaType="ArrayList" select="studentss" column="tid"/>
    </resultMap>
    <select id="studentss" resultType="student">
        select * from student where tid = #{tid};
    </select>

Q.E.D.


如人饮水、冷暖自知