Springboot+Mybatis整合PageHelper

一、全部的gradle引入

// https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter
compile (group: 'com.github.pagehelper', name: 'pagehelper-spring-boot-starter', version: '1.2.10'){
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}

// https://mvnrepository.com/artifact/com.google.code.gson/gson
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'

// https://mvnrepository.com/artifact/com.zaxxer/HikariCP
compile group: 'com.zaxxer', name: 'HikariCP', version: '3.3.1'
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.15'

// https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter
compile (group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '2.0.0'){
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}

// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
compile (group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.1.2.RELEASE'){
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-json'
}
compile group: 'org.springframework.boot', name: 'spring-boot-starter-log4j2', version: '2.1.2.RELEASE'

二、PageHelper的配置
   application.yml

pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql

三、使用实例

public List<ChatAgentPO> getAgentAllPage(int start){
    PageHelper.startPage(start, 2);
    return dao.selectAllPage();
}

四、更多参考官网

五、一个注意点

PageHelper 方法使用了静态的 ThreadLocal 参数,分页参数和线程是绑定的。
只要你可以保证在 PageHelper 方法调用后紧跟 MyBatis 查询方法,这就是安全的。因为 PageHelper 在 finally 代码段中自动清除了 ThreadLocal 存储的对象。
如果代码在进入 Executor 前发生异常,就会导致线程不可用,这属于人为的 Bug(例如接口方法和 XML 中的不匹配,导致找不到 MappedStatement 时), 这种情况由于线程不可用,也不会导致 ThreadLocal 参数被错误的使用。
但是如果你写出下面这样的代码,就是不安全的用法:
    PageHelper.startPage(1, 10);
    List<Country> list;
    if(param1 != null){
         list = countryMapper.selectIf(param1);
    } else {
         list = new ArrayList<Country>();
    }
这种情况下由于 param1 存在 null 的情况,就会导致 PageHelper 生产了一个分页参数,但是没有被消费,这个参数就会一直保留在这个线程上。当这个线程再次被使用时,就可能导致不该分页的方法去消费这个分页参数,这就产生了莫名其妙的分页。
上面这个代码,应该写成下面这个样子:
    List<Country> list;
    if(param1 != null){
        PageHelper.startPage(1, 10);
        list = countryMapper.selectIf(param1);
    } else {
    list = new ArrayList<Country>();
    }
这种写法就能保证安全。
如果你对此不放心,你可以手动清理 ThreadLocal 存储的分页参数,可以像下面这样使用:
List<Country> list;
if(param1 != null){
PageHelper.startPage(1, 10);
try{
list = countryMapper.selectAll();
} finally {
PageHelper.clearPage();
}
} else {
list = new ArrayList<Country>();
}
原文地址:https://www.cnblogs.com/yoyotl/p/10491913.html