Mybatis應用學習(4)——延遲加載 原

1. 通過resultMap實現延遲加載

    1. 通過resultMap中的子標籤association和collection可以實現一對一、一對多、多對多查詢,通過還可以通過這兩標籤實現延遲加載

    2. 應用場景:比如查詢NoteBook相關數據並關聯查詢User信息,如果暫時只需要NoteBook數據而不需要User,那麼僅查詢NoteBook信息即可,如果需要User信息時,在關聯查詢User。

    3. 延遲加載:先從單表查詢所需要的數據,如果需要關聯表中的數據,那麼就進行關聯查詢,可以提高性能,因爲單表查詢比多表聯合查詢要快。

    4. 通過mybatis的啓動配置文件開啓延遲加載:通過settings標籤來開啓延遲加載,添加如下標籤後即可進行延遲加載

	<settings>
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>

    5. 通過association標籤實現:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.NoteBookDao">

	<!-- 先進行單表查詢,然後通過 resultMap實現延遲加載,
	完整的SQL語句可以寫爲
	select *,
	(select cn_user_name from cn_user where cn_user_id=cn_notebook.cn_user_id) cn_user_name,
	(select cn_user_password from cn_user where cn_user_id=cn_notebook.cn_user_id) cn_user_password,
	from cn_notebook where cn_notebook_id=#{cn_notebook_id} 
	resultMap中的association就相當於括號內的子查詢語句
	-->
	<select id="lazyLoadingQuery" parameterType="string" resultMap="lazyLoading">
		select * from cn_notebook where cn_notebook_id=#{cn_notebook_id}
	</select>
	<!-- 通過 resultMap實現延遲加載-->
	<resultMap type="entity.UserAndNoteBook2" id="lazyLoading">
		<id column="cn_notebook_id" property="cn_notebook_id"/>
		<result column="cn_user_id" property="cn_user_id"/>
		<result column="cn_notebook_type_id" property="cn_notebook_type_id"/>
		<result column="cn_notebook_name" property="cn_notebook_name"/>
		<result column="cn_notebook_desc" property="cn_notebook_desc"/>
		<result column="cn_notebook_createtime" property="cn_notebook_createtime"/>
		<!-- 對關聯查詢用戶信息進行延遲加載,主要通過下面兩個屬性實現
		select:指定要延遲執行的SQL語句的id,可以寫當前Mapper映射文件中的SQL也可以寫其他Mapper映射文件中的
		column:指定將Notebook表中與User表建立關聯關係的列,通過該列來進行關聯查詢
		 -->
		<association property="user" javaType="entity.User" select="lazyLoadingQueryUser" column="cn_user_id">

		</association>				
	</resultMap>
	<!-- 定義延遲執行的SQL語句 -->
	<select id="lazyLoadingQueryUser" parameterType="string" resultType="entity.User">
		select * from cn_user where cn_user_id=#{cn_user_id}
	</select>
</mapper>

    6. 對於collection子標籤也是同樣的用法。

    7. 實際上,不需要resultMap標籤,只需要在Mapper映射文件中定義兩個SQL語句,分別是

	<select id="lazyLoadingQuery" parameterType="string" resultType="entity.NoteBook">
		select * from cn_notebook where cn_notebook_id=#{cn_notebook_id}
	</select>
	<select id="lazyLoadingQueryUser" parameterType="string" resultType="entity.User">
		select * from cn_user where cn_user_id=#{cn_user_id}
	</select>

    在Java代碼中,首先通過lazyLoadingQuery對應的Mapper接口方法,查詢得到NoteBook表對應的NoteBook對象,然後從該對象中取得cn_user_id屬性的值,將該值作爲參數lazyLoadingQueryUser對應的Mapper接口方法的參數,就可以查詢得到對應的User數據

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章