关于mysql:PageHelper在SpringBoot的PostConstruct中不生效

7次阅读

共计 1015 个字符,预计需要花费 3 分钟才能阅读完成。

场景

在应用 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

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

正文完
 0