实体类:

package cn.hm1006.pojo;

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

方式一:

mapper.xml

    <select id="getStudent" resultMap="studentTeacher">
        select * from student;
    </select>
    <!--
    思路:
    1. 查询所有的学生信息
    2.根据查询出来的学生的tid.寻找对应的老师!
    -->
    <resultMap id="studentTeacher" type="Student">
        <result property="id" column="id" />
        <result property="name" column="name"/>
        <!--复杂的属性,我们需要单独处理 对象: association 集合:collection -->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="Teacher">
        select * from teacher  where tid = #{tid};
    </select>

测试类:

image.png

    @Test
    public void getStudent(){
        SqlSession sqlSession = mybatisUtil.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.getStudent();
        for (Student student : studentList) {
            System.out.println(student);
        }
    }

结果:

image.png

方式二:

按照结果嵌套处理:

    <select id="getStudent2" resultMap="studentTeacher2">
        select stu.id sid,stu.name sname,t.tname tname
         from student stu,teacher t 
         where stu.tid = t.tid;
    </select>
    <resultMap id="studentTeacher2" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <collection property="teacher" javaType="Teacher">
            <result property="tname" column="tname"/>
        </collection>
    </resultMap>

测试类:

    @Test
    public void getStudent2(){
        SqlSession sqlSession = mybatisUtil.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.getStudent2();
        for (Student student : studentList) {
            System.out.println(student);
        }
    }

结果:

image.png

Q.E.D.


如人饮水、冷暖自知