關聯集合的獲取(連接查詢 & 分步查詢),延遲加載

關聯集合的獲取(連接查詢 & 分步查詢),延遲加載

關聯集合的獲取和關聯屬性的獲取過程很相似,仍然按照相同的順序進行介紹。

public class College {
    Integer id;
    String name;
    List<Student> students;

}

連接查詢

    public College getCollegeById(Integer id);
    <select id="getCollegeById" resultMap="college">
        select *
        from college, student
        where college.college_id = student.student_college
            and college.college_id = #{id}
    </select>

    <resultMap id="college" type="com.test.entity.College">
        <id column="college_id" property="id"></id>
        <result column="college_name" property="name"></result>
        <collection property="students" ofType="com.test.entity.Student">
            <id property="id" column="student_id"></id>
            <result property="name" column="student_name"></result>
        </collection>
    </resultMap>

注意,colectionofType屬性***一定不能省略,它用來指出集合中的元素的類型***

分步查詢

    <select id="getCollegeById" resultMap="college">
        select *
        from college
        where college.college_id = #{id}
    </select>

    <resultMap id="student" type="com.test.entity.Student">
        <id column="student_id" property="id"></id>
        <result column="student_name" property="name"></result>
        <association property="college" select="com.test.dao.ICollegeDao.getCollegeByIdWithoutDependence" column="id=student_college">
            <id property="id" column="college_id"></id>
            <result property="name" column="college_name"></result>
        </association>
    </resultMap>

雙向關聯分步查詢的問題:無限遞歸,導致堆溢出

當雙向關聯都使用分步查詢時,創建A需要創建B,創建B需要創建A,就這樣一致遞歸下去,導致堆內存溢出。

解決方法,可以使用連接查詢,這樣創建A時不需要調用B的方法。

另一個解決方法就是需要與之關聯的對象提供一個沒有依賴的方法,這樣就不會產生相互依賴。

小結

不要忘記ofType屬性

使用association標籤時,不用指定屬性;但是使用collection時,必須指定bean的類型。

延遲加載問題

  1. 通過全局配置
  2. 通過fetchType屬性配置
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章