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

一.前言

上篇博客中介绍了spring boot集成mybatis的方法,基于上篇文章这里主要介绍如何使用分页插件PageHelper。在MyBatis中提供了拦截器接口,我们可以使用PageHelp最为一个插件装入到SqlSessionFactory,实现拦截器功能。

二.实现

pom.xml文件中添加依赖包

[html]  view plain  copy
  1. <dependency>  
  2.     <groupId>com.github.pagehelper</groupId>  
  3.     <artifactId>pagehelper</artifactId>  
  4.     <version>4.1.0</version>  
  5. </dependency>  

创建MybatisConf类

[html]  view plain  copy
  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中直接使用。

[html]  view plain  copy
  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. }  

该工程"springboot_mybatis_demo2"下载地址: 点击打开链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值