作者简介:大家好,我是smart哥,前中兴通讯、美团架构师,现某互联网公司CTO
联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬
学习必须往深处挖,挖的越深,基础越扎实!
阶段1、深入多线程
阶段2、深入多线程设计模式
阶段3、深入juc源码解析
码哥源码部分
码哥讲源码-原理源码篇【2024年最新大厂关于线程池使用的场景题】
码哥讲源码-原理源码篇【揭秘join方法的唤醒本质上决定于jvm的底层析构函数】
码哥源码-原理源码篇【Doug Lea为什么要将成员变量赋值给局部变量后再操作?】
码哥讲源码【谁再说Spring不支持多线程事务,你给我抽他!】
打脸系列【020-3小时讲解MESI协议和volatile之间的关系,那些将x86下的验证结果当作最终结果的水货们请闭嘴】
上一篇Mybatis源码分析刚讲过PageHelper分页机制【Mybatis源码分析】12-插件PageHelper机制_pageautodialect-优快云博客,但是没有分析reasonable参数,碰到这次自己遇上个坑总结一下。
问题描述及原因
使用Mybatis PageHelper插件做了表的分页查询,要求查询符合某一条件的所有记录做处理,就写了一个迭代器在while循环里对每条记录做处理,直到符合条件的记录都处理完程序返回。代码如下
public class ReconPaymentIterator implements Iterator<ReconPayment> {
private ReconPaymentMapper reconPaymentMapper;
private ReconPaymentExample reconPaymentExample;
private int pageNum=1;
private Iterator<ReconPayment> iterator;
public ReconPaymentIterator(ReconPaymentMapper reconPaymentMapper, ReconPaymentExample reconPaymentExample){
this.reconPaymentMapper=reconPaymentMapper;
this.reconPaymentExample=reconPaymentExample;
}
@Override
public boolean hasNext() {
if(iterator==null||!iterator.hasNext()){
PageHelper.startPage(pageNum++, 1000);
iterator =reconPaymentMapper.selectByExample(reconPaymentExample).iterator();
}
return iterator.hasNext();
}
@Override
public ReconPayment next() {
return iterator.next();
}
}
public class ReconPaymentIteratorTest extends AbstractPcsChannelReconServiceAppTest {
@Resource
private ReconPaymentMapper reconPaymentMapper;
@Test
public void testReconPaymentIterator(){
ReconPaymentIterator reconPaymentIterator = new ReconPaymentIterator(reconPaymentMapper, new ReconPaymentExample());
while (reconPaymentIterator.hasNext()){
reconPaymentIterator.next();
}
}
}
在上面的单元测试中发现出现了死循环,跟踪了一下代码发现原因。PageHelper插件为了统计页数默认在查询数据库记录前会做一次count查询的,在上一篇博客中也有注释,具体在PageInterceptor的intercept方法中。
就是上图标红处,在count查询查询后会调用dialect.afterCount()方法。最终调用的是AbstractHelperDialect的afterCount方法。
在得到总数后会调用Page对象的setTotal方法。
如过开启了reasonable功能,并且用户传入的页数已经大于了总页数,则会将用户传入的pageNum修改为总页数pages,这样在count查询后的分页记录查询中导致查询的是最后一页而不会出现期待的遍历结束。
找到配置文件原来这个锅得自己背,从其他项目复制过来的配置文件直接用了没注意开启了reasonable参数。