MyBatis深入解讀懶加載的實現(xiàn)
懶加載 ,也稱為嵌套查詢
需要查詢關(guān)聯(lián)信息時,使用 Mybatis 懶加載特性可有效的減少數(shù)據(jù)庫壓力, 首次查詢只查詢主表信息,關(guān)聯(lián)表的信息在用戶獲取時再加載。
Mybatis 一對一關(guān)聯(lián)的 association 和一對多的 collection 可以實現(xiàn)懶加載。懶加載時要 使用resultMap,不能使用 resultType 。
這里我們以員工表和部門表為例

通過deptId 與 部門表 id 關(guān)聯(lián)
我們這里首先需要開啟一個設(shè)置
<settings>
<!--指定哪些方法去觸發(fā)延遲加載,hashCode,equals,clone,toString-->
<setting name="lazyLoadTriggerMethods" value=""/>
</settings>懶加載功能是默認開啟的, 但這里我們也需要設(shè)置這個屬性, 不設(shè)置則不會觸發(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(); //提交事務(wù)
sqlSession.close(); //關(guān)閉查詢結(jié)果 :

通過結(jié)果可以看到 , 當我們第一次輸出這個 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>
懶加載就介紹到這里,感謝閱讀
到此這篇關(guān)于MyBatis深入解讀懶加載的實現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis懶加載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringCloud URL重定向及轉(zhuǎn)發(fā)代碼實例
這篇文章主要介紹了SpringCloud URL重定向及轉(zhuǎn)發(fā)代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03
springboot詳解實現(xiàn)車險理賠信息管理系統(tǒng)代碼
本系統(tǒng)基于Springboot開發(fā)實現(xiàn)了一個為用戶車險進行理賠信息管理的一個信息化管理系統(tǒng),核心的業(yè)務(wù)主要是用戶申請保險理賠,管理員審核進入理賠程序,事故調(diào)查員對事故進行調(diào)查和現(xiàn)場勘察,這其中共涉及到三類用戶,購買保險的客戶,事故調(diào)查員和系統(tǒng)管理員2022-06-06
java實現(xiàn)圖像轉(zhuǎn)碼為字符畫的方法
這篇文章主要為大家詳細介紹了java實現(xiàn)圖像轉(zhuǎn)碼為字符畫的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03

