首页 > 其他 > 详细

【MyBatis】嵌套查询

时间:2021-01-27 10:01:17      阅读:51      评论:0      收藏:0      [点我收藏+]

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>

 

【MyBatis】嵌套查询

原文:https://www.cnblogs.com/cckong/p/14333248.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!