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



一.前言

上篇博客中介绍了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 }
复制代码

猜你喜欢

转载自blog.csdn.net/chen213wb/article/details/80531494
今日推荐