Mybatis多对一和一对多

Mybatis多对一 一对多

思想:所有我们无法直接得到的结果,都需要使用ResultMap结果集映射
结果集映射,需要保证返回的对象的属性和数据库查询出来的字段一一对应。
一对多就是以以为中心在属性字段时一的老师应该做调整
多对一就是以多为中心 在属性字段时多的学生类应该做调整

我们这里有两张 表
1老师表 老师中有id name
2学生表 学生表中有id name tid(老师的id)
如何使用Mybatis查出学生表中老师的信息是问题的关键,我们无法直接得到teacher的tid所以这里就要使用ResultMap来映射。
在创建实体类的时候应该注意,在创建tid时类型应当为老师类,不能是简单的int

多对一

<resultMap id="StudentTeacher" type="student">

  <result column="sid" property="id"></result>
    <result column="sname" property="name"></result>
    <association property="tid" javaType="teacher">
        <result column="tid" property="id"></result>
        <result column="tname" property="name"></result>
     </association>

</resultMap>
<select id="getStudent"  resultMap="StudentTeacher">

  select s.id sid,s.name sname,t.id tid,t.name tname
from student s, teacher t
where s.id=t.id

</select>

一对多
学生类正常写老师类加一个集合

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxr.mapper.TeacherMapper">

    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
        <collection property="students" ofType="Student">
            <result property="id" column="sid"></result>
            <result property="name" column="sname"></result>
            <result property="tid" column="tid"></result>
        </collection>
    </resultMap>
    <select id="getTeacher" resultMap="TeacherStudent">
     select s.id sid,s.name sname,t.id tid,t.name tname
from student s, teacher t
where s.id=t.id and t.id=#{id}
</select>
        </mapper>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值