MyBatis 多对一

多对一:我的个人理解就是在类与类之间有has关系,解决的是sql查询时数据库内是外键关联的关系,teacher只有id与student对应,没有与id对应的值;用多对一来解决值得问题
多:student


@Data//lombok
public class Student {
    private int id;
    private String name;
    private Teacher teacher;
}

一:teacher

@Data
public class Teacher {
    private int ID;
    private String name;
}

多个学生对应一个老师:

两种方式实现:

public interface StudentMapper {
    List<Student> getAllStudent();//方法一
    List<Student> getAllStudent2();//方法二
}

方法一对应的xml

<!--    多对一 方式一 -->
<select id="getAllStudent" resultMap="SttudenttTeacher">
    select * from student
</select>
    <select id="getTeacherById" parameterType="_int" resultType="teacher">
        select * from teacher where id=#{id};
    </select>
    <resultMap id="SttudenttTeacher" type="student">
<!-- property Student类的属性名     javaType 属性的类名    column 表内对应的列名   select 对应子查询的id-->
        <association property="teacher" javaType="teacher" column="tid" select="getTeacherById"></association>
    </resultMap>

方式二对应的xml:

<!--    多对一  方式二-->
    <select id="getAllStudent2" resultMap="SttudenttTeacher2">
        select  s.id id,s.name name,t.name tname from student s,teacher t where s.tid= t.id;
    </select>
    <resultMap id="SttudenttTeacher2" type="student">
        <result property="id" column="id"></result>
        <result property="name" column="name"></result>
        <association property="teacher" javaType="teacher">

            <result column="tname" property="name"></result>
        </association>
    </resultMap>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值