springboot集成mybatis源码分析-mybatis的mapper执行查询时的流程(三)
springboot集成mybatis源碼分析-mybatis的mapper執(zhí)行查詢時的流程(三)
例:
package com.example.demo.service;import com.example.demo.dao.UserDao; import com.example.demo.domain.User; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import java.util.List;@Service @Slf4j public class UserService {@Autowiredprivate UserDao userDao;public List<User> getUser(){List<User> userList = userDao.getUser();log.info("查詢出來的用戶信息,{}",userList.toString());return userList;} }當(dāng)userService中的getUser方法執(zhí)行的時候,userDao.getUser()是怎么走的?
1、在springboot項目啟動時,加載mybatis相關(guān)配置,同事會在MapperRegister中保存mapper的代理類,在創(chuàng)建UserService bean的時候,需要注入userDao類,但userDao類是一個Interface類型,所以在注入的時候其實是注入的一個mapper代理類,也就是MapperProxy類
2、當(dāng)執(zhí)行userDao.getUser()時,會走M(jìn)apperProxy中的invoke方法,最終是通過mapperMethod.execute(sqlSession. args)
3、進(jìn)入MapperMethod的execute方法,會根據(jù)select、insert、update 來走不同的方法
4、本次測試時走的是SELECT 的case,在該case中會判斷是否有返回值(返回值得處理器),因本次查詢返回值是一個list,所以會走executeForMany()
5、進(jìn)入到executeForMany中,參數(shù)是SQLSessionTemplate和null,進(jìn)行處理后,進(jìn)入到sqlsession.<E>selectList(*, *)中
6、該selectList方法調(diào)用的是SQLSessionTemplate類的selectList
?7、進(jìn)入到sqlSessionProxy(該代理類其實就是DefaultSqlSession)的selectList方法中,參數(shù)statement就是mapper方法,paramter為null,
在selectList方法中,會從Configuration對象中獲取statement對應(yīng)的對象,然后通過執(zhí)行器executor的query來執(zhí)行
8、進(jìn)入到executor的query方法中,當(dāng)前的executor默認(rèn)是CachingExecutor
9、進(jìn)入到CachingExecutor的query方法中,在當(dāng)前方法中會先獲取相應(yīng)的BindSql,然后會創(chuàng)建cache
10、進(jìn)入到createCacheKey方法中,該方法其實是BaseExecutor中的方法
11、創(chuàng)建完成之后,會調(diào)用query方法,在方法中,會先查詢cache,沒有再調(diào)用delegate的query方法
?
12、delegate是BaseExecutor(執(zhí)行器),在當(dāng)前方法中也會先從緩存中查詢,查詢不到在從庫中查詢
?
13、進(jìn)入queryFormDatabase方法中,在方法中會將之前創(chuàng)建的cacheKey保存到localCache中,然后在執(zhí)行doQuery方法
?
14、進(jìn)入到doQuery方法中,也就是默認(rèn)的simpleExecutor中
?
15、進(jìn)入到configuration.newStatementHandler中(默認(rèn)statement為preparedStatement)
?
16、返回preparestatementHandler處理器,然后調(diào)用prepareStatement方法
?
?
18、在方法中會通過prepareStatement的execute來查詢數(shù)據(jù)庫,完畢后,會在handeler中處理返回數(shù)據(jù)
?
19、處理返回數(shù)據(jù)是在DefaultResultSetHandler類中
?
20、處理完成后悔返回一個list<Object>對象
?
posted @ 2019-03-06 18:24 犇犇丶 閱讀(...) 評論(...) 編輯 收藏
總結(jié)
以上是生活随笔為你收集整理的springboot集成mybatis源码分析-mybatis的mapper执行查询时的流程(三)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot集成mybatis源
- 下一篇: idea使用dababase tools