今天遇到一個問題,MyBatis分頁插件失效,導致分頁無效,分頁失效的原因是我在Controller里做了分頁,但業務邏輯實現類對應的方法卻寫了兩個SQL,第一個SQL是查詢一條數據判斷,第二個SQL是查詢列表(是需要分頁的),結果通過日志打印SQL,我發現它卻對第一個SQL做分頁。最后我的解決辦法是,在業務邏輯實現類對應的方法做分頁,解決了這個問題。
MyBatis實現分頁很簡單,需要引入如下兩個依賴(以SpringBoot+MyBatis為例):
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.12</version> </dependency>
核心模板代碼:
PageHelper.startPage(pageNum,pageSize); List<T> list = xxxService.getAll(); PageInfo<T> pageInfo = new PageInfo<>(list);
通常建議這段代碼寫入Service層,最好不要寫在Controller里面。