关于mysql: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

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理