使用环境:若以前后端分离,Spring Boot
问题提出:若以自带了一个startPage();
方法,只对该语句以后的第一个查询(Select)语句得到的数据进行分页。但是有的业务需要通过sql将数据查询出来,通过Java代码进行逻辑运算。再次分页查询,如果继续使用startPage();
会导致分页查询出来的数据不是预期数据。那么可以使用一下代码,将数据从数据库中全部查询出来,最后在进行分页封装
1. 代码场景
- controller层
/**
* 查询评分列表
*/
@PreAuthorize("@ss.hasPermi('system:maines:list')")
@GetMapping("/list")
public TableDataInfo list(VoteMain voteMain, @RequestParam int pageNum, @RequestParam int pageSize) {
// 分页查询
startPage();
List<VoteMain> list = voteMainService.selectVoteMainList(voteMain);
return getDataTable(list);
}
- service层代码
@Override
public List<VoteMain> selectVoteMainList(VoteMain voteMain) {
// 找出指定数据
List<VoteMain> voteMains = voteMainMapper.selectVoteMainList(voteMain);
voteMains.forEach(main -> {
// 代码省略,看下面就行 根据逻辑插入集合中的成员变量0或者1
main.setUserEvaluateStatus(userNoCompleteNum.equals("0") ? "1" : "0");
});
// 查询用户的状态 0或者1 这个时候 分页查询会失效。他只会找出第四行的制定页数的数据也就是pageSize,经过筛选后,可能只会有几条数据,这并不符合预期的分页查询
voteMains = voteMains.stream().filter(res -> {
return res.getUserEvaluateStatus().equals(voteMain.getUserEvaluateStatus());
}).collect(Collectors.toList());
return voteMains;
}
2. 解决方案
查询除所有的数据,最后在controller层进行分页封装.这里是对做了一个逻辑判断,如果要使用逻辑运行后的字段筛选再查出所有的数据,进行二次分页封装。如果不是就是用startPage();service层代码不变,这样避免了每次加载都要找出所有
- controller层
/**
* 查询评分列表
*/
@PreAuthorize("@ss.hasPermi('system:maines:list')")
@GetMapping("/list")
public TableDataInfo list(VoteMain voteMain, @RequestParam int pageNum, @RequestParam int pageSize) {
if (voteMain.getUserEvaluateStatus() != null) {
//分页不起作用,手动分页
List<VoteMain> list = voteMainService.selectVoteMainList(voteMain);
return getTableDataInfo(pageNum, pageSize, list);
} else {
startPage();
List<VoteMain> list = voteMainService.selectVoteMainList(voteMain);
return getDataTable(list);
}
}
private TableDataInfo getTableDataInfo(@RequestParam int pageNum, @RequestParam int pageSize, List<?> scoreList) {
int total = scoreList.size();
int startIndex = (pageNum - 1) * pageSize;
int endIndex = Math.min(startIndex + pageSize, total);
List<?> pagedScoreList = scoreList.subList(startIndex, endIndex);
return new TableDataInfo(pagedScoreList, total);
}
小结总结
在使用startPage();分页查询的时候,如果在实体类中写入pageNum和pageSize字段,会出现莫名其妙的错误。如若遇到建议去掉。