mybatis_11.一對多的處理

一對多處理

好比:一個老師擁有多個學生!java

對於老師而言,就是一對多的關係!面試

環境搭建

  1. 環境搭建,和剛纔同樣

實體類sql

@Data
public class Student {

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

}
@Data
public class Teacher {
    private int id;
    private String name;

    //一個老師擁有多個學生
    private List<Student> students;
}

按照結果嵌套處理

<!--按結果嵌套查詢-->
    <select id="getTeacher" 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="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--複雜的屬性,咱們須要單獨處理 對象: association 集合: collection
        javaType="" 指定屬性的類型!
        集合中的泛型信息,咱們使用ofType獲取
        -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

按照查詢嵌套處理

<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from mybatis.teacher where id = #{tid}
</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.student where tid = #{tid}
</select>

小結

  1. 關聯 - association 【多對一】
  2. 集合 - collection 【一對多】
  3. javaType & ofType
    1. JavaType 用來指定實體類中屬性的類型
    2. ofType 用來指定映射到List或者集合中的 pojo類型,泛型中的約束類型!

注意點:mybatis

  • 保證SQL的可讀性,儘可能保證通俗易懂
  • 注意一對多和多對一中,屬性名和字段的問題!
  • 若是問題很差排查錯誤,能夠使用日誌 , 建議使用 Log4j

慢SQL 1s 1000s優化

面試高頻日誌

  • Mysql引擎
  • InnoDB底層原理
  • 索引
  • 索引優化!
相關文章
相關標籤/搜索