mybatis复杂结果集映射

本文深入探讨了数据库查询中多对一及一对多的数据映射方法,通过具体的SQL语句与MyBatis配置示例,解析了如何在多表查询中正确处理学生与老师之间的关联关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多对一映射

多个学生对映一个老师

在这里插入图片描述
在这里插入图片描述

    <!--多表查询-->
    <select id="getAllStudent" resultMap="getAllStudent">
        select sid,sname,t.tid,name from student s,teacher t
        where s.tid = t.tid
    </select>
    <!--处理结果集-->
    <resultMap id="getAllStudent" type="student">
        <id property="sid" column="sid"></id>
        <result property="sname" column="sname"></result>
   <!--处理老师类型-->
        <association property="teacher" javaType="teacher">
            <id property="tid" column="tid"></id>
            <result property="name" column="name"></result>
        </association>
    </resultMap>

测试结果:
在这里插入图片描述

一对多映射

在这里插入图片描述
在这里插入图片描述

select t.tid,name,sid,sname from student s,teacher t
where s.tid = t.tid and t.tid = #{tid}

<resultMap id="getTeacher" type="teacher">
    <id property="tid" column="tid"></id>
    <result property="name" column="name"></result>
    <!-- 集合对应的泛型用oftype-->
    <collection property="students" ofType="student">
        <id column="sid" property="sid"></id>
        <result column="sname" property="sname"></result>
    </collection>
</resultMap>

测试结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值