[Mybatis]5.多对一、一对多

例子为5个学生,对应1个老师。
表结构为:
image

student的tid为外键,关联teacher的id。

多对一

现要查询所有学生,附带上老师的信息(包括姓名)。可以用两种方式,1.嵌套处理结果集映射 2.嵌套处理查询

1.写实体类

Student实体类:

    private int id;
    private String name;
    private Teacher teacher;

Teacher实体类

    int id;
    String name;

2.写xml

方法一 嵌套处理结果集映射
    <select id="getStudents" resultMap="studentTeacher">
        select s.id sid, s.name sname,t.id tid, t.name tname  from mybatis1.student s,mybatis1.teacher t where s.tid = t.id
    </select>
    <resultMap id="studentTeacher" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="id" column="tid"/>
            <result property="name" column="tname"/>
        </association>
    </resultMap>

<association> 为联合,用于映射一个对象(Teacher),使用javaType来指定对象

方法二 嵌套处理查询

先写

    <select id="getStudents2" resultMap="studentTeacher2">
        select * from mybatis1.student
    </select>
    <resultMap id="studentTeacher2" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>

再写

    <select id="getTeacher" resultType="Teacher">
        select * from mybatis1.teacher where id = #{tid}
    </select>

也就是先查询到了tid,然后使用tid再去查询老师的name。

一对多

现要查询一个老师,附带上他所带的所有学生的信息。同样可以用两种方式,**1.嵌套处理结果集映射 2.嵌套处理查询 **

1.写实体类

Student实体类:

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

Teacher实体类

    int id;
    String name;
    private List<Student> students;

2.写xml

方法一 嵌套处理结果集映射
    <select id="getTeacher2" resultMap="TeacherStudent2">
        select t.name tname,t.id tid, s.name sname, s.id sid from mybatis1.student s,mybatis1.teacher t where s.tid = t.id and t.id = #{id}
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
        </collection>
    </resultMap>

<collection 为集合,用于映射一个集合(List<Student>),使用ofType来指定集合中对象的类型

方法二 嵌套处理查询

先写

    <select id="getTeacher" resultMap="TeacherStudent">
        select * from mybatis1.teacher where id = #{id}
    </select>
    <resultMap id="TeacherStudent" type="Teacher">
        <collection property="students"  ofType="Student" column="id" select="getStudents"/>
    </resultMap>

再写

    <select id="getStudents" resultType="Student">
        select * from mybatis1.student where tid = #{id}
    </select>

也就是先查询到了老师的id,然后使用id再去查询学生的信息。

总结:

多对一(映射一个对象)使用association,一对多(映射集合)使用collection
javaType用来指定实体类中属性的类型
ofType用来指定映射到集合中pojo类型

posted @ 2021-11-19 17:17  从零开始学java_wxz  阅读(78)  评论(0)    收藏  举报