PageHelper:MyBatis的物理分页插件,负责将写好的sql语句进行加工分页。
image.png
下面通过例子看看项目中应用PageHelper:
- 导入相关依赖
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
- application.yml 配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
- sql语句及接口对应方法
@Select({"select student.sid as id, student.sname as name, student.grade as grade from student"})
List<Map<String,String>> sqlFindPageAll();
- 在ServiceImpl中定义pagehelper分页方法
public PageInfo<Student> findPageAll(int pageNum, int pageSize) {
/*
PageHelper分页方法,传入的是当前页及每页显示条数
*/
PageHelper.startPage(pageNum, pageSize);
//返回的结果集存放到list中
List<Student> studentList = studentMapper.sqlFindPageAll();
//PageInfo其实是pagehelper给我们封装的一个类,里面有一些我们做分页表常用的属性
PageInfo<Map<String, String>> studentPageInfo = new PageInfo<>(studentList);
return studentPageInfo;
- controller:
public PageInfo<Student> getAllInfo(@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageSize){
PageInfo<Student> page = StudentService.findPageAll(pageNum,pageSize);
return page;
}
}
- MyBatis分页插件说到这里,往后有更多的写法都会在这里更新,谢谢观赏。
网友评论