Mybatis插件001分页 pagehelper


Mybatis-PageHelper/Important.md at master · pagehelper/Mybatis-PageHelper · GitHubMybatis通用分页插件. Contribute to pagehelper/Mybatis-PageHelper development by creating an account on GitHub.https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/Important.md

依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.1</version>
</dependency>

配置

pagehelper:
  helper-dialect: mysql
  params: count=countSql
  reasonable: true
  supportMethodsArguments: true //自动分页参数

startPageoffsetPage

PageHelper.startPage(1, 10);
//PageHelper.offsetPage(1,10);
List<Map<String, String>> tableList = tablesMysql.selectAllTable();
PageInfo<Map<String, String>> mapPageInfo = new PageInfo<>(tableList);

Lambda

PageInfo<Map<String, String>> tableLista = PageHelper.startPage(1, 10)
        .doSelectPageInfo(() -> tablesMysql.selectAllTable());

自动分页参数的问题

如果原先SQL中有 limit,并且入参中带有分页参数,则pageHelper会自动执行分页,所以就出现了SQL最后拼接了两个limit导致SQL报错

  1. protected static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>();
  2. 如果使用了startPage(),但是没有执行对应的sql,那么就表明,当前线程ThreadLocal被设置了分页参数,可是没有被使用,当下一个使用此线程的请求来时,就会出现问题。
  3. 如果程序在执行sql前,发生异常了,就没办法执行finally当中的clearPage()方法,也会造成线程的ThreadLocal被污染。
  4. 所以,官方给我们的建议,在使用PageHelper进行分页时,执行sql的代码要紧跟startPage()方法。
  5. 除此之外,我们可以手动调用clearPage()方法,在存在问题的方法之前。
  6. 需要注意:不要分页的方法前手动调用clearPage,将会导致你的分页出现问题。

posted @ 2023-06-09 23:14  drlsk  阅读(11)  评论(0)    收藏  举报  来源