MyBatis 多对一操作

数据库表结构

 

学生表多对一老师表

XML中的两种书写方式:

方式一:子查询

<select id="getStudent" resultMap="StudentMapper">
    select * from student;
</select>

<resultMap id="StudentMapper" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>

<select id="getTeacher" resultType="Teacher">
    select * from teacher where id=#{id};
</select>

方式二:链表查询

<select id="getStudent2" resultMap="StudentTeacher">
    SELECT
        s.id sid,
        s.name sname,
        T.name tname
    FROM
        student s,
        teacher T
    WHERE
        s.tid = T.id;
</select>

<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
    </association>
</resultMap>

测试文件

public class MyTest {

    @Test
    public void getTeacherTest() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> student = mapper.getStudent2();

        for (Student student1 : student) {
            System.out.println(student1);
        }

        sqlSession.close();
    }
}

 

posted @ 2021-09-14 11:11  你的小可爱吖  阅读(52)  评论(0编辑  收藏  举报