五、Mybatis按结果嵌套查询

前言

Myatis官方文档结果映射

一、多对一嵌套结果查询。
实体类:

@Data
public class Student {

    private int id;
    private String name;
    private int tid;

    //多对一
    private Teacher teacher;
}

StudentMapper接口:

List<Student> getStudentAndTeacher(@Param("id") int id);

StudentMapper.xml:

<!--嵌套结果查询-->
<select id="getStudentAndTeacher" resultMap="getStudentTeacher">
    SELECT s.id sid,s.name sname,t.id tid,t.name tname FROM student s,tearcher t WHERE s.`tid`= #{id}
</select>
<resultMap id="getStudentTeacher" type="com.zhy.entity.Student">
    <id property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" column="tid">
        <id property="id" column="tid"/>
        <result property="name" column="tname"/>
    </association>
</resultMap>

二、一对多嵌套结果查询。
实体类:

@Data
public class Teacher {

    private int id;
    private String name;

    //一对多
    private List<Student> students;

}

TeacherMapper接口:

Teacher getTeacherAndStudent();

TeacherMapper.xml:

<!--嵌套结果查询-->
<select id="getTeacherAndStudent" resultMap="getTeacherStudent">
    SELECT t.`id` tid,t.`name` tname,s.`id` sid,s.`name` sname FROM tearcher t,student s WHERE t.`id`=s.`tid`
</select>
<resultMap id="getTeacherStudent" type="com.zhy.entity.Teacher">
    <id property="id" column="tid"/>
    <result property="name" column="tname"/>
    <collection property="students" ofType="com.zhy.entity.Student">
        <id property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
        <association property="teacher" column="tid">
            <id property="id" column="tid"/>
            <result property="name" column="tname"/>
        </association>
    </collection>
</resultMap>

三、注意。

  1. 多对一使用association关联,一对多使用collection集合。
  2. javaType指实体类中属性的类型,ofType指泛型类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值