MyBatis深入解讀懶加載的實現(xiàn)
懶加載 ,也稱為嵌套查詢
需要查詢關聯(lián)信息時,使用 Mybatis 懶加載特性可有效的減少數(shù)據(jù)庫壓力, 首次查詢只查詢主表信息,關聯(lián)表的信息在用戶獲取時再加載。
Mybatis 一對一關聯(lián)的 association 和一對多的 collection 可以實現(xiàn)懶加載。懶加載時要 使用resultMap,不能使用 resultType 。
這里我們以員工表和部門表為例
通過deptId 與 部門表 id 關聯(lián)
我們這里首先需要開啟一個設置
<settings> <!--指定哪些方法去觸發(fā)延遲加載,hashCode,equals,clone,toString--> <setting name="lazyLoadTriggerMethods" value=""/> </settings>
懶加載功能是默認開啟的, 但這里我們也需要設置這個屬性, 不設置則不會觸發(fā)延遲加載功能
Employee selectOneEmployee(int id);
我們以查詢單個員工為例 , resultMap 與sql 如下
<!--定義resultMap--> <resultMap id="employeeMap1" type="Employee"> <id column="id" property="id"/> <result property="name" column="name"/> <result property="age" column="age"/> <!--fetchType為查詢的類型,這里選擇lazy select為嵌套查詢--> <association property="dept" javaType="Dept" fetchType="lazy" select="selectDept" column="deptId"> <result column="name" property="name"/> </association> </resultMap> <select id="selectOneEmployee" resultMap="employeeMap1"> select id,name,age,deptId from employee where id=#{id} </select> <!--通過上一級sql提供的deptId查詢--> <select id="selectDept" resultType="Dept"> select name from dept where id=#{deptId} </select>
此處一對一 ,我們使用<association>
java測試 :
public static void main(String[] args) { SqlSession sqlSession= MybatisUtil.getSqlSession(); EmployeeDao mapper=sqlSession.getMapper(EmployeeDao.class); Employee employee = mapper.selectOneEmployee(3); System.out.println(employee); System.out.println(employee.getDept()); sqlSession.commit(); //提交事務 sqlSession.close(); //關閉
查詢結果 :
通過結果可以看到 , 當我們第一次輸出這個 employee 對象時, 部門是沒有被查詢的 , 而當我們需要使用到部門的信息時, 才會去觸發(fā)這個查詢
查詢部門 resultMap 與 sql如下:
<resultMap id="deptMap1" type="Dept"> <id column="id" property="id"/> <result column="name" property="name"/> <!--collection為一對多 , 這里一個部門包含多個員工--> <collection property="list" javaType="List" ofType="Employee" select="selectEmployee" fetchType="lazy" column="id"> <result property="name" column="name"/> </collection> </resultMap> <select id="selectOneDept" resultMap="deptMap1"> SELECT id,name FROM dept where id=#{id} </select> <select id="selectEmployee" resultType="Employee"> select name from employee where deptId=#{id} </select>
一對多,我們使用<collection>
懶加載就介紹到這里,感謝閱讀
到此這篇關于MyBatis深入解讀懶加載的實現(xiàn)的文章就介紹到這了,更多相關MyBatis懶加載內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于@RequestParam與@RequestBody使用對比
這篇文章主要介紹了@RequestParam與@RequestBody的使用對比,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10