PageHelper是一款非常好用的分页插件,它和Mybatis工作在一起,可以大幅提升开发效率。PageHelper是通过Mybatis的拦截器插件原理实现的。
1. pom.xml配置
在我们的Spring Boot工程中增加PageHelper的配置,请记住PageHelper是和Mybatis工作在一起的,因此务必要引入Mybatis的jar包。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
2. 向Spring容器中注入PageHelper
@Configuration
public class PageHelperConfiguration {
private static final Logger log = LoggerFactory.getLogger(PageHelperConfiguration.class);
@Bean
public PageHelper pageHelper() {
log.info("------Register MyBatis PageHelper");
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
//通过设置pageSize=0或者RowBounds.limit = 0就会查询出全部的结果。
p.setProperty("pageSizeZero", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
3. 在代码中使用PageHelper
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserMapper userMapper;
@RequestMapping(value = "/queryall.do", method = RequestMethod.GET)
public PageInfo<User> queryAll( @RequestParam(value = "pageNum", required = false, defaultValue="1") Integer pageNum,
@RequestParam(value = "pageSize", required = false, defaultValue="10") Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> list = userMapper.selectAllUsers();
PageInfo<User> pageInfo = new PageInfo<User>(list);
return pageInfo;
}
}
其余代码请参考:http://www.jianshu.com/p/9e8a7c07c60b
Mybatis分页插件PageHelper官网:https://github.com/pagehelper/Mybatis-PageHelper
Mybatis之插件原理:[http://blog.csdn.net/hupanfeng/article/details/9247379]