一.前言
上篇博客中介绍了spring boot集成mybatis的方法,基于上篇文章这里主要介绍如何使用分页插件PageHelper。在MyBatis中提供了拦截器接口,我们可以使用PageHelp最为一个插件装入到SqlSessionFactory,实现拦截器功能。
二.实现
pom.xml文件中添加依赖包
1 2 3 4 5
| <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.0</version> </dependency>
|
创建MybatisConf类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| package com.woniu.mybatisconf; import java.util.Properties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.github.pagehelper.PageHelper; /* * 注册MyBatis分页插件PageHelper */ @Configuration public class MybatisConf { @Bean public PageHelper pageHelper() { System.out.println("MyBatisConfiguration.pageHelper()"); PageHelper pageHelper = new PageHelper(); Properties p = new Properties(); p.setProperty("offsetAsPageNum", "true"); p.setProperty("rowBoundsWithCount", "true"); p.setProperty("reasonable", "true"); pageHelper.setProperties(p); return pageHelper; } }
|
这时就可以使用PageHelp插件了,在controller中直接使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package com.woniu.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.github.pagehelper.PageHelper; import com.woniu.bean.User; import com.woniu.mapper.UserMaper; @RestController @RequestMapping("/web") public class WebController { @Autowired private UserMaper mapper; @RequestMapping("/index") public List<User> selectAge(int age){ /* * 第一个参数是第几页;第二个参数是每页显示条数。 */ PageHelper.startPage(1,2); return mapper.Select(age); } }
|
该工程”springboot_mybatis_demo2”下载地址: 点击打开链接