Mybatis-lesson09-多对一查询 (查询所有的学生及对应的老师信息)方法二-结果嵌套查询-03-13

第二种方法,采用结果查询:但老师的ID 要和学生的TID有个对应关系

注意事宜:SQL语句需加上 t.id tid 如果不注明 查出来的老师ID 则为O

<select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.name tname, t.id  tid
    from student s, teacher t
    where s.tid =t.id
</select>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.feijian.dao.StudentMapper">

    <!--方法二:结果嵌套查询-->
    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname, t.id  tid
        from student s, teacher t
        where s.tid =t.id
    </select>

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

<!--方法一:子查询-->
<!--1、查询所有学生的信息
    2、根据查询出来的学生tid,寻找对应的老师-->

    <select id="getStudent" resultMap="StudentTeacher">
        select * from student;
    </select>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++   -->
    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂属性要单独处理
            对象:association  在一个表中查询另外一张表,在sql中就叫子查询
            集合:collection-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++   -->

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

</mapper>
posted @ 2023-03-13 07:09  Rui2022  阅读(40)  评论(0编辑  收藏  举报