【Mybatis源码分析】13-记一次PageHelper reasonable参数使用不当造成的死循环

上一篇Mybatis源码分析刚讲过PageHelper分页机制https://blog.csdn.net/shenchaohao12321/article/details/80168655,但是没有分析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参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值