1:Java 通过Stream流对 list 集合数据直接分页 (该场景适用于list数据已经获取到了,通常不是通过mysql数据库中获取到)
public static void main(String[] args) {
List<String> asList = Arrays.asList("1", "2", "3", "4");
Integer currentPageNumber = 1;//当前页
Integer pageMaxSize = 3;//每页条数
List<String> collect1 = asList.stream().skip((currentPageNumber - 1) * pageMaxSize).limit(pageMaxSize).collect(Collectors.toList());
System.out.println(JSONUtils.toJSONString(collect1));
}
2:Java从数据库中通过sql的形式查询到的 list 集合数据进行分页 -
1).添加分页插件相关依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
<exclusions>
<exclusion>
<artifactId>mybatis-spring-boot-starter</artifactId>
<groupId>org.mybatis.spring.boot</groupId>
</exclusion>
</exclusions>
</dependency>
2).springboot配置文件配置插件启动
mybatis:
# mapper 位置
mapper-locations: classpath:**/mapper/*.xml
# 驼峰标识转换
configuration:
map-underscore-to-camel-case: true
# 分页插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
3:代码层面是处理
@GetMapping(value = "/getVillageByPage", produces = {"application/json;charset=UTF-8"})
public Result getVillageByPage(String param) {
try {
VillageInfo villageInfo = JSON.parseObject(param, VillageInfo.class);
PageInfo<VillageInfo> page =
PageHelper.startPage(villageInfo.getPageNo(), villageInfo.getPageSize())
.doSelectPageInfo(
() -> villageService.getVillageByPage(villageInfo)
);
return new Result(ResultCodeEnum.SUCCESS, page);
} catch (Exception e) {
log.warn("小区查询(分页)接口请求异常", e);
return new Result(ResultCodeEnum.ERROR);
}
}
当然pagehelper插件的使用也会遇到坑 ,最好了解一下该插件分页的原理。