【MyBatis】嵌套查询

1.嵌套查询(子查询)

 想要这样在一个查询结果里还有一个对象  

不能用sql语句的嵌套查询(联表查询):因为那样查出来的是一个 表的属性  而不是 一个对象。

在StudentMapper里面建立如下两种映射

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

    <resultMap id="StudentTeacher" type="com.lei.pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂的属性,我们需要单独处理 对象: association 集合: collection -->
        <association property="teacher" column="tid" javaType="com.lei.pojo.Teacher" select="getTeacher"/>
    </resultMap>

    <select id="getStuTea" resultMap="StudentTeacher">
        select * from mybatis.student
    </select>



    <select id="getTeacher" resultType="com.lei.pojo.Teacher">
        select * from mybatis.teacher where id = #{id}
    </select>

还可以这样

 <!--按照结果嵌套处理-->
    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname
        from mybatis.student s,mybatis.teacher t
        where s.tid = t.id;
    </select>

    <resultMap id="StudentTeacher2" type="com.lei.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="com.lei.pojo.Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>
原文地址:https://www.cnblogs.com/cckong/p/14333248.html