Mybatis Plus整合PageHelper分頁的實現示例
Mapper Plus自帶分頁PaginationInterceptor物件,雖然說目前沒有什麼問題,並且使用簡單,但是個人感覺有個弊端:目前個人使用中,想要用Mapper Plus自帶的分頁功能的話需要在mapper物件中傳入一個Page物件才可以實現分頁,這樣耦合度是不是太高了一點,從web到service到mapper,這個Page物件一直都在傳入,這樣的使用讓人感覺有點麻煩,但是Mapper Plus不得不說真的是很好用的。
PageHelper用過的人多多少少了解,這個框架要實現分頁只要一行程式碼,所以我的想法是將兩個好用的框架整合在一起。
1. pom引入
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.3</version> <exclusions> <exclusion> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </exclusion> <exclusion> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> </exclusion> </exclusions> </dependency> <!-- Mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.0</version> </dependency>
我用的是Spring Boot框架,在pom中直接引入Mapper Plus和PageHelper就可以了;而使用的PageHelper包是整合SpringBoot的包,個人感覺這種版本的只需要在配置檔案中配置即可開箱試用非常便捷,但是這個包必須要去掉內建的mybatis依賴,不然會和Mapper Plus中的版本不一致
2. 配置檔案
Mapper Plus的配置我就貼出來了,主要貼出PageHelper的配置
############# 分頁外掛PageHelper配置 ############# pagehelper.helper-dialect=mysql pagehelper.reasonable=true pagehelper.support-methods-arguments=true pagehelper.pageSizeZero=true pagehelper.params=count=countSql
3. 使用
使用起來很方便,我用一個controller鐘的list介面作為示範
@GetMapping("/list") public Result list(@ParamCheck(notNull = false) Integer projectType,@ParamCheck(notNull = false) Integer projectStatus,@ParamCheck(notNull = false) String departmentId,@ParamCheck(notNull = false) String name,@ParamCheck(defaultValue = Constant.PAGE) Integer page,@ParamCheck(defaultValue = Constant.SIZE) Integer size){ if (page > 0 && size > 0){ PageHelper.startPage(page,size); } List<OaProjectDTO> list = projectService.list(projectType,projectStatus,departmentId,name); PageInfo pageInfo = new PageInfo<>(list); return ResultUtil.success(pageInfo); }
PageHelper.startPage(page,size);這一行程式碼就實現了分頁,而我做了一個判斷的原因是,如若資料是要不分頁展示所有的,那就不需要啟動這行程式碼。
最後通PageInfo物件將資料包裝返回即可。
到此這篇關於Mybatis Plus整合PageHelper分頁的實現示例的文章就介紹到這了,更多相關Mybatis Plus PageHelper分頁內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!