zoukankan      html  css  js  c++  java
  • PageHelper在SpringBoot的@PostConstruct中不生效

    场景

    在使用PageHelper的过程中,出现了一个很奇怪的问题,假设在数据库中存放有30条Country记录,我们用下面的方法使用PageHelper进行分页查询,那么我们希望得到的page.size是10。

    PageHelper.startPage(1, 10);
    List<Country> list = countryMapper.selectAll();
    PageInfo page = new PageInfo(list);
    assertEquals(10, list.size());
    

    一般情况下结果是如我们所愿的,但是当下面的代码放到SpringBoot中标明@PostConstruct的方法下后,查询结果就是30而不是10,让我们一起来看看其中的原因。

    @Component
    public class PageHelperProblem {
    
        @Autowired
        CountryMapper countryMapper;
    
        @PostConstruct
        public void init() {
            PageHelper.startPage(1, 10);
    	  List<Country> list = countryMapper.selectAll();
    	  PageInfo page = new PageInfo(list);
    	  assertEquals(10, list.size());
        }
    }

    原因

    debug之后发现,在执行完代码PageHelper.startPage(1, 10)之后,我们把pageSize和pageNum设置到ThreadLocal中去了,但是在执行下一行代码之前,理论上应该进入到PageInterceptor拦截器中给sql动态的加上limit条件。但是没有进去,原因在于Bean的PostConstruct执行的时候,Pagehelper的autoconfigure还没有初始化,故而拦截器还没有创建出来,所以导致的结果就是startPage只是把分页参数设置到了ThreadLocal中去了,但是却没有被拦截器拦截,所以导致了分页失败,没有达到预期的分页效果。

    参考文章:

    https://www.liangzl.com/get-article-detail-132917.html

    https://github.com/pagehelper/pagehelper-spring-boot/issues/38

    本篇文章如有帮助到您,请给「翎野君」点个赞,感谢您的支持。

  • 相关阅读:
    0593. Valid Square (M)
    0832. Flipping an Image (E)
    1026. Maximum Difference Between Node and Ancestor (M)
    0563. Binary Tree Tilt (E)
    0445. Add Two Numbers II (M)
    1283. Find the Smallest Divisor Given a Threshold (M)
    C Primer Plus note9
    C Primer Plus note8
    C Primer Plus note7
    C Primer Plus note6
  • 原文地址:https://www.cnblogs.com/lingyejun/p/13772957.html
Copyright © 2011-2022 走看看