Spring Boot中的pagehelper插件真的很好用,结合Mybatis框架,两行代码就可以实现分页功能。但是,正因为它的使用太简单了,导致我从来没有想过去深入了解它的原理。直到这次犯了一个很蠢的错误,所以决定进一步认识认识它。
首先介绍一下它的使用吧,两步完成。
1、在pom.xml文件中加入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
2、在代码中添加分页代码
//给参数设置默认值
int pageNum = requestJson.get("pageNum") != null ? Integer.valueOf(String.valueOf(requestJson.get("pageNum"))) : 1;
int pageSize = requestJson.get("pageSize") != null ? Integer.valueOf(String.valueOf(requestJson.get("pageSize"))) : 10;
//startPage() 方法应该在查询语句之前
//pageNum 当前页码 pageSize 页面数据量
PageHelper.startPage(pageNum, pageSize);
List<Map<String , Object>> listData = securityCheckDao.selectAllQuestionType(requestJson);
//将查询出来的列表丢到PageInfo()里就可以了
PageInfo pageInfo = new PageInfo(listData);
这样得到的pageInfo 里面就包含分页所需要的全部信息,直接返回给前端就完成了。
而我遇到的问题是,希望将查出的数据列表listData 进行树排序,再将它放进PageInfo()里返回给前端。结果发现这样操作是有问题的。
PageHelper.startPage(pageNum, pageSize);
List<Map<String , Object>> listData = securityCheckDao.selectAllQuestionType(requestJson);
//TreeConstructionUtils.buildTree()为树排序方法
PageInfo pageInfo = new PageInfo(TreeConstructionUtils.buildTree(listData));
这样返回的数据个数是不对的,真实数据有14条,而返回的只有4条。不管我如何改变pageSize的值,都是这样。
于是我看了一下查询语句,才豁然开朗,原来pagehelper是这样工作的。
SELECT
t1.id,
t1.dict_name AS dictName,
date_format(t1.update_time , '%Y-%m-%d') AS updateTime,
t1.parent_id AS parentId,
t2.dict_name AS parentName,
t1.`level`
FROM
tt_sys_dict t1
LEFT JOIN tt_sys_dict t2 ON t1.parent_id = t2.id
WHERE t1.dict_code = 'questionType'
order by t1.update_time DESC LIMIT ?
这是控制台打印的查询语句,大家发现最后的LIMIT 函数没,这个在我的mapper里是没有写的,是pagehelper加上去。我顿时觉得,对于一个初级程序员的我来说,还有好多要学的。
PageHelper.startPage(pageNum, pageSize)这个地方设置的两个值,pagehelper会在你执行查询语句的时候帮你加上去,也就是LIMIT 的两个参数,第一个参数是LIMIT 的起始下标,pagehelper会根据pageNum和pageSize自动给你算出;第二个参数是LIMIT的 数据量,也就是pageSize。而且我发现,pagehelper会执行两遍你写的查询语句,第一遍会进行count(0),查出总条数,第二遍就会利用你设置的参数帮你分页查询出pageSize条数据。
我之前想先进行树排序后再进行分页的想法,在使用pagehelper时是行不通的,因为会影响pagehelper的自动分页。因此我得出在进行pagehelper分页的时候不可以给查询出的数据进行其他排序操作(查询语句中写order by是可以的),这可能就是pagehelper的局限之处,不过我相信应该有解决办法,等我找到了再分享出来。