[Mybatis]一对多的处理(重点)

85 阅读1分钟

举例

比如:一个老师拥有多个学生! 对于一个老师而言,就是一对多的关系!

环境搭建

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    private int id;
    private String name;
    /**
     * 一个老师拥有多个学生
     */
    private List<Student> students;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {

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

}

查询方式

按照结果集嵌套查询(简单,推荐使用)

<!--按结果集嵌套查询-->
    <select id="getTeacherNew" resultMap="TeacherStudent">
        select s.id sid,s.name sname,t.name tname,t.id tid
        from student s,teacher t
        where s.tid=t.id and t.id=#{tid}
    </select>
    <resultMap id="TeacherStudent" type="com.mybatisstudy.pojo.Teacher">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
        <!--复杂的属性 单独处理 对象:association 集合:collection
        javaType="" 指定属性的类型
        集合中的泛型信息 用ofType获取
        -->
        <collection property="students" ofType="com.mybatisstudy.pojo.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="TeacherAndStudent">
    select * from teacher where id =#{tid}
</select>
<resultMap id="TeacherAndStudent" type="com.mybatisstudy.pojo.Teacher">
    <collection property="students" column="id" javaType="ArrayList" ofType="com.mybatisstudy.pojo.Student" select="getStudentByTeacherId"></collection>
</resultMap>

<select id="getStudentByTeacherId" resultType="com.mybatisstudy.pojo.Student">
    select * from student where tid = #{tid}
</select>

小结

1.关联 - association 多对一

2.集合 - collection 一对多

3.javaType & ofType

  • javaType 用来指定实体类和中属性的类型
  • ofType 用来指定映射到list或者集合中的pojo类型,泛型中的约束类型!

注意点

  • 保证sql的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名和字段的问题
  • 如果问题不好排查错误,可以使用日志