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底層原理
  • 索引
  • 索引優化
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章