MyBatis-一对多、多对一

一对多和多对一,是一个相对的概念。

以老师和学生为例,最常见的情况就是:一个老师教授很多学生。站在学生的角度,是很多学生被一个老师教,即很多学生关联一个老师(多对一);站在老师的角度,是一个老师教授很多学生,即一个老师有多个学生(一对多)。

在MyBatis中,处理多对一的问题使用 association标签(关联);处理一对多的问题使用 collection标签(集合)。

多对一

按照查询嵌套处理

查询所有的学生信息。

根据查询出来的学生的tid,寻找对应的老师。

<select id="getStudent" resultMap="StudentTeacher">
        select * from mybatis_test.student;
</select>
<resultMap id="StudentTeacher" type="Student">
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <association column="tid" property="teacher" javaType="Teacher" select="getTeacher" />
</resultMap>
<select id="getTeacher" resultType="Teacher">
        select * from mybatis_test.teacher where id = #{id};
</select>

按照结果嵌套处理

<select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname from mybatis_test.student s,mybatis_test.teacher t where s.tid = t.id;
</select>
<resultMap id="StudentTeacher2" type="Student">
        <result column="sid" property="id"/>
        <result column="sname" property="name"/>
        <association property="teacher" javaType="Teacher">
            <result column="tname" property="name"/>
        </association>
</resultMap>

一对多

按照查询嵌套处理

 <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from mybatis_test.teacher;
 </select>
<resultMap id="TeacherStudent2" type="Teacher">
        <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
        select * from mybatis_test.student where tid = #{id}
</select>

按照结果嵌套处理

 <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid,s.name sname,t.name tname,t.id tid
        from mybatis_test.student s,mybatis_test.teacher t
        where s.tid = t.id;
 </select>
 <resultMap id="TeacherStudent" type="Teacher">
        <result column="tid" property="id"/>
        <result column="tname" property="name"/>
        <collection property="students" ofType="Student">
            <result column="sid" property="id"/>
            <result column="sname" property="name"/>
            <result column="tid" property="tid"/>
        </collection>
 </resultMap>

按照结果嵌套处理和按照查询嵌套处理,分别对应了sql中的联表查询和子查询。

总结

  1. 多对一:关联,使用association
  2. 一对多:集合,使用collection
  3. javaType 和 ofType的区别
    • JavaType 用来指定实体类中属性的类型
    • ofType 用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型

需要注意的是:

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

SQL 语句写的不好,会出现慢SQL的问题(查询时间过长)。

MySql的面试高频问点

  • MySql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章