SpringBoot学习四:整合Mybatis分页插件 Page
2018-08-06 本文已影响151人
yuluo
引入maven依赖
按照惯例,需要引入SpringBoot的pagehelper依赖。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
请注意版本号,与Mybatis不兼容的版本号可能会导致异常
配置pagehelper参数
#mybatis配置
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: online.suiyu.mybatisdemo.entity
server:
port: 8083
#配置pagehelper
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
详细配置参数参考官方文档
依次修改Controller、Service,添加分页的参数
- Controller层
@ApiOperation(value = "getAllUser", notes = "获取所有的内容", tags = "user")
@RequestMapping(value = "/getalluser", method = RequestMethod.GET)
public List<User> getAllUser(@RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize", required = false, defaultValue = "4") int pageSize) {
return userService.getAllUser(pageNum, pageSize);
}
- Service层
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getAllUser(int pageNum, int pageSize) {
//这是整个过程中最核心的一条语句
PageHelper.startPage(pageNum, pageSize);
return userMapper.getAllUser();
}
}
到此完成,顺便一提,当pageNum<=0
时,加载第一页,当pageNum>最后一页
则加载最后一页。这是有配置文件中的reasonable: true
决定的!
到此,整合完成!