PageHelper does not work in @ postconstruct of springboot

Time:2020-11-8

scene

In the process of using PageHelper, there is a very strange problem. Suppose that there are 30 country records stored in the database, we use the following method to perform paging query with PageHelper, then we hope to get page.size It’s 10.

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

Generally, the result is what we want, but when the following code is put into the method marked @ postconstruct in springboot, the query result is 30 instead of 10. Let’s take a look at the reasons.

@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());
    }
}

reason

After debugging, it is found that after the code is executed PageHelper.startPage After (1, 10), we set PageSize and pagenum to ThreadLocal. However, before executing the next line of code, we should theoretically enter the pageinterceptor to add a limit condition to SQL dynamically. The reason is that the autoconfigure of the PageHelper has not been initialized when the bean postconstruct is executed, so the interceptor has not been created. Therefore, the result is that the startpage only sets the paging parameters to ThreadLocal, but it is not intercepted by the interceptor. As a result, paging fails and the expected paging effect is not achieved 。

Reference articles:

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

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

If this article is helpful to you, please give “Lingye Jun” a compliment, thank you for your support.