1.應(yīng)用場景
? ? 1.PageHelper的底層實現(xiàn)
? ? 2.@Autowired private HttpServletRequest request 或者 @Autowired private HttpSession session
? ? ? ? ? 其底層實現(xiàn)為Spring對單例對象注入非單例實例的一個解決方案:Scoped Proxy户敬, Spring巧妙地注入了一個裝飾器代理了真實對象的操作左腔。再繼續(xù)往底層挖,實則是最終在代理邏輯中最后調(diào)用的是RequestContextHolder.currentRequestAttributes()
1.1分析ThreadLocal實現(xiàn)存取數(shù)據(jù)的方式
2.Mybatis分頁插件的再分析
1.mybatis的分頁插件就是使用了ThreadLocal來存放分頁的數(shù)據(jù),從而對Service層實現(xiàn)無侵入的分頁實現(xiàn)
2.1關(guān)于注冊mybatis Plugin
Mybatis的Plugin,實際上對應(yīng)的是org.apache.ibatis.plugin.Interceptor接口粥帚,因為Intercepter的核心方法是plugin(Object target)方法,而對于該方法的實現(xiàn),需要通過org.apache.ibatis.plugin.Plugin的靜態(tài)方法wrap(Object target, Interceptor interceptor)對對應(yīng)對象進行攔截再產(chǎn)生一個代理對象,說白了就是封裝為Page對象時,會實現(xiàn)一個攔截器,攔截器基于Plugin中的一個wrap()方法對對象進行攔截,最后進行目標(biāo)增強產(chǎn)生一個代理對象
在mybatis核心配置文件SqlMapConfig中注冊分頁插件
<plugins>
? ? ?<!-- com.github.pagehelper 為 PageHelper 類所在包名 -->
? ? ?<plugin interceptor="com.github.pagehelper.PageHelper">
? ? ? ? ? ? <!-- 設(shè)置數(shù)據(jù)庫類型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL 六種數(shù)據(jù)庫-->? ? ? ? ? ? ? ?<property name="dialect" value="mysql"/>
? ? ? </plugin>
</plugins>
2.2PageHelper
PageHelper攔截的是org.apache.ibatis.executor.Executor的query方法,傳參的核心原理就是通過ThreadLocal進行的,當(dāng)我們需要對某個查詢進行分頁查詢時,我們可以調(diào)用Mapper進行查詢前調(diào)用一次PageHelper.startPage(..),這樣PageHelper會把分頁信息存入一個ThreadLocal變量中,在攔截到query方法執(zhí)行時會從對應(yīng)的ThreadLocal中獲得分頁信息,進行分頁處理完之后,清理ThreadLocal中的分頁信息,使得每次的使用互不影響,同時對原來的查詢代碼沒有熱河的侵入性灰蛙。
一般返回結(jié)果是一個java.util.List,? ?Pagehelper分頁查詢后的結(jié)果會變成一個PageHelper分頁查詢后的結(jié)果會變成com.github.pagehelper.Page類型祟剔,其繼承了java.util.ArrayList,所以不會對我們的方法聲明造成影響缕允。
簡單使用:
public void test() {
? ? int pageNum = 2;//頁碼峡扩,從1開始
????int pageSize = 10;
????//每頁記錄數(shù)
?????PageHelper.startPage(pageNum, pageSize);
????//指定開始分頁
????UserMapper userMapper = this.session.getMapper(UserMapper.class);
????List<User> all = userMapper.findAll(); Page<User> page = (Page<User>) all;
????System.out.println(page.getPages()); System.out.println(page);
}
參考原文地址:https://blog.csdn.net/elim168/article/details/72820509?作者:elim168