方式一:使用原生的PageHelper
1.在pom.xml中引入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
2.在springboot的启动类(Application.java)里面注入配置
@Bean
PageHelper pageHelper(){
//分页插件
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("reasonable", "true");
properties.setProperty("supportMethodsArguments", "true");
properties.setProperty("returnPageInfo", "check");
properties.setProperty("params", "count=countSql");
pageHelper.setProperties(properties);
//添加插件
new SqlSessionFactoryBean().setPlugins(new Interceptor[]{pageHelper});
return pageHelper;
}
方式二:使用PageHelper的starter
1.在pom.xml中引入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
2.在application.properties配置pagehelper的属性
#pagehelper分页插件配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
使用方法:
1.在查询语句之前插入下列语句:
PageHelper.startPage(pageNum, pageSize);
2.属性介绍:
System.out.println("当前页:"+pageInfo.getPageNun());
System.out.println("每页显示记录数:"+pageInfo.getPageSize());
System.out.println("总页数:"+pageInfo.getPages());
System.out.println("总记录数:"+pageInfo.getTotal());
System.out.println("是否有上一页:"+pageInfo.isHasPreviousPage());
System.out.println("是否有下一页:"+pageInfo.isHasNextPage());
System.out.println("导航页面:"+Arrays.toString(pageInfo.getNavigatepageNums()));
例如:
1.在service层写入
public PageInfo<VisitorRecord> getVisitorRecordByCondition(Map<String, Object> condition, int pageNum,Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<VisitorRecord> visitorRecord = visitorRecordDao.getVisitorRecordByCondition(condition);
PageInfo<VisitorRecord> pageInfo = new PageInfo<>(visitorRecord);
return pageInfo;
}
2.控制器层
PageInfo<VisitorRecord> visitorRecord = visitorRecordService.getVisitorRecordByCondition(condition, pageNumber / pageSize + 1, pageSize);
System.out.println("总记录数:"+visitorRecord.getTotal());