1. 經過resultMap中的子標籤association和collection能夠實現一對1、一對多、多對多查詢,經過還能夠經過這兩標籤實現延遲加載java
2. 應用場景:好比查詢NoteBook相關數據並關聯查詢User信息,若是暫時只須要NoteBook數據而不須要User,那麼僅查詢NoteBook信息便可,若是須要User信息時,在關聯查詢User。mybatis
3. 延遲加載:先從單表查詢所須要的數據,若是須要關聯表中的數據,那麼就進行關聯查詢,能夠提升性能,由於單表查詢比多表聯合查詢要快。app
4. 經過mybatis的啓動配置文件開啓延遲加載:經過settings標籤來開啓延遲加載,添加以下標籤後便可進行延遲加載性能
<settings> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> </settings>
5. 經過association標籤實現:spa
<?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子標籤也是一樣的用法。code
7. 實際上,不須要resultMap標籤,只須要在Mapper映射文件中定義兩個SQL語句,分別是xml
<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數據對象