1. 程式人生 > >mybatis 延遲載入

mybatis 延遲載入

1、什麼是延遲載入

  1. 延遲載入的條件:resultMap可以實現高階對映(使用association、collection實現一對一及一對多對映),association、collection具備延遲載入功能。
  2. 延遲載入的好處: 先從單表查詢、需要時再從關聯表去關聯查詢,大大提高 資料庫效能,因為查詢單表要比關聯查詢多張錶速度要快。
  3. 延遲載入的例項: 如果查詢訂單並且關聯查詢使用者資訊。如果先查詢訂單資訊即可滿足要求,當我們需要查詢使用者資訊時再查詢使用者資訊。把對使用者資訊的按需去查詢就是延遲載入。

    2、如何開啟延遲載入功能

  4. Mybatis的延遲載入功能預設是關閉的
  5. 需要在SqlMapConfig.xml檔案中通過setting標籤配置來開啟延遲載入功能
  6. 開啟延遲載入的屬性: lazyLoadingEnabled:全域性性設定懶載入。如果設為‘false’,則所有相關聯的都會被初始化載入。預設為false aggressiveLazyLoading:當設定為‘true’的時候,懶載入的物件可能被任何懶屬性全部載入。否則,每個屬性都按需載入。預設為true
  7. 配置

     <settings>
         <!--開啟延遲載入-->
         <setting name="lazyLoadingEnabled" value="true"/>
         <!--關閉積極載入-->
         <setting name="aggressiveLazyLoading" value="false"/>
     </settings>

    3、延遲載入的resultMap

  8. 在resultMap中使用association或者collection,即可使用延遲載入。
  9. 延遲載入需要兩個statement語句來完成
  10. 在resultMap中使用association或者collection來配置兩個statement直接的管理
  11. resultMap程式碼 :

     <!--查詢訂單和建立訂單的使用者,使用延遲載入-->
     <resultMap id="OrderAndUserLazyLoad" type="Orders">
         <id column="id" property="id"/>
         <result column="user_id" property="userId" />
         <result column="number" property="number" />
         <result column="createtime" property="createtime" />
         <result column="note" property="note" />
         <!--
         select:要延遲載入的statement的id
         colunm:關聯兩張表的那個列的列名
          -->
         <association property="user" javaType="User" select="findUser" column="user_id">
    
         </association>
     </resultMap>

    4、延遲載入的mapper檔案

  12. 必須要有兩個statement
  13. 兩個statement直接必須存在關聯的資料列

     <select id="findOrdersByLazyLoad" resultMap="OrderAndUserLazyLoad">
         SELECT * FROM orders
     </select>
    
     <select id="findUser" parameterType="int" resultType="User">
         SELECT * FROM User WHERE id = #{value}
     </select>

    5、mapper介面

    public List

    6、測試程式碼

    public void testFindOrdersByLazyLoad() throws Exception{ SqlSession session = sessionFactory.openSession(); Mapper mapper = session.getMapper(Mapper.class); //只會傳送查詢訂單資訊的SQL List

7、總結

  1. 不使用mybatis提供的association及collection中的延遲載入功能,如何實現延遲載入?? 實現方法如下: 定義兩個mapper方法: 1、查詢訂單列表 2、根據使用者id查詢使用者資訊 實現思路: 先去查詢第一個mapper方法,獲取訂單資訊列表 在程式中(service),按需去呼叫第二個mapper方法去查詢使用者資訊。

  2. 總之: 使用延遲載入方法,先去查詢簡單的sql(最好單表,也可以關聯查詢),再去按需要載入關聯查詢的其它資訊。