天天看點

mybatis延遲加載政策 懶加載例子

什麼是延遲加載

延遲加載就是在需要用到資料才進行加載,不需要用到資料時就不加載資料,延遲加載也稱懶加載,      

好處

先從當表查詢,需要時再從關聯表去關聯查詢,大大提高資料庫性能,因為查詢單表又比關聯查詢多表速度要快。      

壞處

因為隻有當需要用到資料時才會進行資料庫查詢。這樣在大批量資料查詢時,<br/>
  因為查詢工作也要消耗時間,是以可能會造成使用者等待時間,并常造成使用者體驗下降。      

例子

接口

List<Score> findAllLazy();      

xml

<!--
    懶加載 一對一
        1.隻查詢 成績
        2.使用<association  select 調用查詢學生的接口  fetchType="lazy" 設定為懶加載-->
    <select id="AllLazy" resultType="student">
          select * from  student_tb where id=#{id}
    </select>
    <resultMap id="StudentListLazyMap" type="score">
        <id property="scoreid" column="scoreid"></id>
        <result property="coursename" column="coursename"></result>
        <result property="score" column="score"></result>
        <result property="studentid" column="studentid"></result>

        <association property="student" javaType="student" column="studentid"  select="AllLazy" fetchType="lazy"></association>
    </resultMap>
    <select id="findAllLazy" resultMap="StudentListLazyMap">
          select * from  score_tb;
    </select>      

測試結果

沒有開啟懶加載

開啟懶加載

開啟全局懶加載

<settings>
      <!--
          将資料庫_的字段改為駝峰式寫法  tb:student_name  映射為  studentName
      -->
      <setting name="mapUnderscoreToCamelCase" value="true"/>

      <!-- 開啟全局懶加載-->
      <setting name="lazyLoadingEnabled" value="true"/>
      <setting name="aggressiveLazyLoading" value="false"/>


      <!--開啟二級緩存-->
      <setting name="cacheEnabled" value="true"/>

  </settings>