MyBatis学习笔记(十二)一对多关系的两种实现形式

(十二)一对多的关系

通过老师查找到自己的学生。

和上一篇比较像,因此只粘贴Mapper.xml文件,主要是其中的思想比较重要,其实数据库字段是什么不重要。

大家看着理解,还是比较有意思的。

直接进行联表查询

<select id="getTeacher" resultType="top.zhang.pojo.Teacher">
    select * from teacher
</select>

<select id="getTeacherById" resultMap="teacherstudent">
    select t.id tid,t.name tname,s.id sid,s.name sname
    from teacher t,student s
    where t.id = s.tid and tid = #{tid}
</select>

<resultMap id="teacherstudent" type="top.zhang.pojo.Teacher">
    <result property="id" column="tid"></result>
    <result property="name" column="t.name"></result>
    <collection property="students" ofType="top.zhang.pojo.Student">
        <result property="id" column="sid"></result>
        <result property="name" column="sname"></result>
    </collection>
</resultMap>

使用结果进行查询

<select id="getTeacherById2" resultMap="teacherstudent2">
    select *
    from teacher
    where id = #{tid}
</select>

<resultMap id="teacherstudent2" type="top.zhang.pojo.Teacher">
    <collection property="students" column="id" ofType="top.zhang.pojo.Student" select="getStudent"></collection>
</resultMap>

<select id="getStudent" resultType="top.zhang.pojo.Student">
    select *
    from student
    where tid = #{id}
</select>

一对多种可能比上一篇多对一稍微难一点,但是基本思路是一样的,多看几遍代码会有收获!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值