一、什麼是延遲加載
resultMap可實現高級映射(使用association、collection實現一對一及一對多映射),association、collection具備延遲加載功能。
需求:
如果查詢訂單並且關聯查詢用戶信息。如果先查詢訂單信息即可滿足要求,當我們需要查詢用戶信息時再查詢用戶信息。把對用戶信息的按需去查詢就是延遲加載。
延遲加載:先從單表查詢,需要時再從關聯表去關聯查詢,大大提高數據庫性能,因爲查詢單表要比關聯查詢多張錶速度要快。
二、使用association實現延遲加載
1、需求:查詢訂單並且關聯查詢用戶信息
2、mapper.xml
需要定義兩個mapper的方法對應的statement。
1) 只查詢訂單信息
SELECT * FROM orders
在查詢訂單的statement中使用association去延遲加載(執行)下邊的statement。
<!-- 查詢訂單關聯查詢用戶,用戶信息需要延遲加載 -->
<select id="findOrdersUserLazyLoading" resultMap="OrderUserLazyLoadingResultMap">
SELECT * FROM orders
</select>
resultMap怎麼寫,看下面的3。
2) 關聯查詢用戶信息
通過上邊查詢到的訂單信息中user_id去關聯查詢用戶信息
使用UserMapper.xml中的findUserById
<select id="findUserById" resultType="user" parameterType="int">
SELECT * FROM USER WHERE id=#{value}
</select>
3) 執行思路:
上邊先去執行findOrdersuserLazyLoading,當需要的時候再去執行findUserById,通過resultMap的定義將延遲加載執行配置起來。
3、延遲加載的resultMap
<resultMap type="cn.itcast.mybatis.po.Orders" id="OrderUserLazyLoadingResultMap">
<!-- 對訂單信息進行映射配置 -->
<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(是根據user_id查詢用戶信息是statement)
要使用UserMapper.xml中findUserById完成根據用戶id(user_id)對用戶信息的查詢,如果findUserById不在本mapper中,
需要前邊加namespace
column:訂單信息中關聯用戶信息的列,是user_id
-->
<association property="user" javaType="cn.itcast.mybatis.po.User"
select="cn.itcast.mybatis.mapper.UserMapper.findUserById" column="user_id">
</association>
</resultMap>
使用association中是select指定延遲加載去執行的statement的id。
4、打開延遲加載開關
<settings>
<!-- 打開延遲加載的開關 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 將積極加載改爲消息加載即按需加載 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
lazyLoadingEnabled:設置懶加載,默認爲false。如果爲false:則所有相關聯的都會被初始化加載。
aggressiveLazyLoading:默認爲true。當設置爲true時,懶加載的對象可能被任何懶屬性全部加載;否則,每個屬性按需加載。
三、使用collection實現延遲加載
同理。
四、思考總結
1.不使用mybatis提供的association及collection中的延遲加載功能,如何實現延遲加載?
實現思路:
定義兩個mapper方法:
1) 查詢訂單列表 2)根據用戶id查詢用戶信息
先去查詢第一個mapper方法,獲取訂單信息列表;在程序中(service),按需去調用第二個mapper方法去查詢用戶信息。
2.總結
使用延遲加載方法,先去查詢簡單的sql(最好單表,也可關聯查詢),再去按需加載關聯查詢的其他信息。