1. 程式人生 > >Spring Boot系列教程八: Mybatis使用分頁插件PageHelper

Spring Boot系列教程八: Mybatis使用分頁插件PageHelper

tid bind color clas owb 如何 cto 集成 使用

一.前言

上篇博客中介紹了spring boot集成mybatis的方法,基於上篇文章這裏主要介紹如何使用分頁插件PageHelper。在MyBatis中提供了攔截器接口,我們可以使用PageHelp最為一個插件裝入到SqlSessionFactory,實現攔截器功能。

二.實現

pom.xml文件中添加依賴包

1         <dependency>
2             <groupId>com.github.pagehelper</groupId>
3             <artifactId>pagehelper</artifactId>
4
<version>4.1.0</version> 5 </dependency>

創建MybatisConf類

 1 package com.woniu.mybatisconf;
 2 
 3 import java.util.Properties;
 4 
 5 import org.springframework.context.annotation.Bean;
 6 import org.springframework.context.annotation.Configuration;
 7 
 8 import
com.github.pagehelper.PageHelper; 9 10 /* 11 * 註冊MyBatis分頁插件PageHelper 12 */ 13 14 @Configuration 15 public class MybatisConf { 16 @Bean 17 public PageHelper pageHelper() { 18 System.out.println("MyBatisConfiguration.pageHelper()"); 19 PageHelper pageHelper = new
PageHelper(); 20 Properties p = new Properties(); 21 p.setProperty("offsetAsPageNum", "true"); 22 p.setProperty("rowBoundsWithCount", "true"); 23 p.setProperty("reasonable", "true"); 24 pageHelper.setProperties(p); 25 return pageHelper; 26 } 27 }

這時就可以使用PageHelp插件了,在controller中直接使用。

 1 package com.woniu.controller;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.RestController;
 8 
 9 import com.github.pagehelper.PageHelper;
10 import com.woniu.bean.User;
11 import com.woniu.mapper.UserMaper;
12 
13 @RestController
14 @RequestMapping("/web")
15 public class WebController {
16     @Autowired
17     private UserMaper mapper;
18     
19     
20     @RequestMapping("/index")
21     public List<User> selectAge(int age){
22         /*
23          * 第一個參數是第幾頁;第二個參數是每頁顯示條數。
24          */
25         PageHelper.startPage(1,2);
26         return mapper.Select(age);
27     }
28 }

Spring Boot系列教程八: Mybatis使用分頁插件PageHelper