SpringBoot_Mybatis_分页

分页分为两种:逻辑分页和物理分页。

逻辑分类就是:一次性从数据库获取所有数据,再通过后端的代码获取正确的分页。

物理分页就是:通过数据库直接获取分页数据,例如编写带有limit的MySQL语句。

使用SpringBoot和Mybatis连接MySQL数据库实现物理分页,原理上都是基于limit关键字实现的。有以下三种方法:

1、在mapper.xml文件中直接编写limit语句。limit n,m的意思是偏移量为n,获取m行数据。例如limit 5,10也就是获取6-15行的数据。

2、编写拦截器实现,解决不断编写limit语句的问题。原理就是,在mapper.xml中编写普通的SQL语句,执行查询之前,通过获取方法参数,为SQL语句加上limit关键词。第三种方法的原理就是如此。

3、Mybatis分页插件PageHelper。

下面是第3种的实现方法。

1、引入依赖。

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

2、两句代码解决。

            String orderBy = "info_id desc";//排序字段 空格 排序方式
            //设置分页和排序
            PageHelper.startPage(1,10, orderBy);
            //获取分页数据
            List<InfosResponse> infoList = infoService.getInfoList(integer);
            //获取分页信息
            PageInfo<InfosResponse> pageInfo = new PageInfo<>(infoList);

大致原理如下:

package com.github.pagehelper;

@Intercepts({@Signature(
    type = Executor.class,
    method = "query",
    args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
), @Signature(
    type = Executor.class,
    method = "query",
    args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}
)})
public class PageInterceptor implements Interceptor {
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            Object[] args = invocation.getArgs();
            MappedStatement ms = (MappedStatement)args[0];
            //mapper中方法传入的参数,目前只有我们原始定义的
            Object parameter = args[1];
            RowBounds rowBounds = (RowBounds)args[2];
            ResultHandler resultHandler = (ResultHandler)args[3];
            //sql执行器
            Executor executor = (Executor)invocation.getTarget();
            CacheKey cacheKey;
            BoundSql boundSql;
            if (args.length == 4) {
                boundSql = ms.getBoundSql(parameter);
                cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
            } else {
                cacheKey = (CacheKey)args[4];
                boundSql = (BoundSql)args[5];
            }

            this.checkDialectExists();
            List resultList;
            if (!this.dialect.skip(ms, parameter, rowBounds)) {
                if (this.dialect.beforeCount(ms, parameter, rowBounds)) {
                    //获取总数据量
                    Long count = this.count(executor, ms, parameter, rowBounds, resultHandler, boundSql);
                    if (!this.dialect.afterCount(count, parameter, rowBounds)) {
                        Object var12 = this.dialect.afterPage(new ArrayList(), parameter, rowBounds);
                        return var12;
                    }
                }
                //执行sql语句,包括了插入limit
                resultList = ExecutorUtil.pageQuery(this.dialect, executor, ms, parameter, rowBounds, resultHandler, boundSql, cacheKey);
            } else {
                resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
            }

            Object var16 = this.dialect.afterPage(resultList, parameter, rowBounds);
            return var16;
        } finally {
            if (this.dialect != null) {
                this.dialect.afterAll();
            }

        }
    }
}
package com.github.pagehelper.util;
public abstract class ExecutorUtil {
    public static <E> List<E> pageQuery(Dialect dialect, Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql, CacheKey cacheKey) throws SQLException {
        if (!dialect.beforePage(ms, parameter, rowBounds)) {
            return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
        } else {
            //经过这一步之后,多了两个传入的参数First_PageHelper Second_PageHelper 对应的应该就是limit n,m中的n,m
            parameter = dialect.processParameterObject(ms, parameter, boundSql, cacheKey);
            //在原来的语句上多了limit ?
            String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, cacheKey);
            BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameter);
            Map<String, Object> additionalParameters = getAdditionalParameter(boundSql);
            Iterator var12 = additionalParameters.keySet().iterator();

            while(var12.hasNext()) {
                String key = (String)var12.next();
                pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
            }
            //交给mybatis执行语句了
            return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, pageBoundSql);
        }
    }

}

以上纯属个人理解的表层原理。

PageInterceptor 是一个Mybatis的拦截器,拦截了query的操作。对这些操作进行加工,也就是limit关键字的插入。这些加工操作发生在了ExecutorUtil 中。

关于使用PageHelper时,为什么要紧跟着查询操作使用

先继续看到ExecutorUtil 中:

     //经过这一步之后,多了两个传入的参数First_PageHelper Second_PageHelper 对应的应该就是limit n,m中的n,m
     parameter = dialect.processParameterObject(ms, parameter, boundSql, cacheKey);

 到PageHelper 中的:(这就和两句代码中的第一句对应上了,我们设置的分页信息在这里被获取了)

package com.github.pagehelper;
public class PageHelper extends PageMethod implements Dialect {
    public Object processParameterObject(MappedStatement ms, Object parameterObject, BoundSql boundSql, CacheKey pageKey) {
        return this.autoDialect.getDelegate().processParameterObject(ms, parameterObject, boundSql, pageKey);
    }
}
package com.github.pagehelper.dialect;    
public abstract class AbstractHelperDialect extends AbstractDialect implements Constant {
    public Object processParameterObject(MappedStatement ms, Object parameterObject, BoundSql boundSql, CacheKey pageKey) {
        Page page = this.getLocalPage();
        ...
    }
}
package com.github.pagehelper.page;
public abstract class PageMethod {
    protected static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal();

    public static <T> Page<T> getLocalPage() {
        return (Page)LOCAL_PAGE.get();
    }
}

接下来套用官方的解释:Mybatis-PageHelper

PageHelper 方法使用了静态的 ThreadLocal 参数,分页参数和线程是绑定的。

只要你可以保证在 PageHelper 方法调用后紧跟 MyBatis 查询方法,这就是安全的。因为 PageHelper 在 finally 代码段中自动清除了 ThreadLocal 存储的对象。

如果代码在进入 Executor 前发生异常,就会导致线程不可用,这属于人为的 Bug(例如接口方法和 XML 中的不匹配,导致找不到 MappedStatement 时), 这种情况由于线程不可用,也不会导致 ThreadLocal 参数被错误的使用。

但是如果你写出下面这样的代码,就是不安全的用法:

PageHelper.startPage(1, 10);
List<User> list;
if(param1 != null){
    list = userMapper.selectIf(param1);
} else {
    list = new ArrayList<User>();
}

这种情况下由于 param1 存在 null 的情况,就会导致 PageHelper 生产了一个分页参数,但是没有被消费,这个参数就会一直保留在这个线程上。当这个线程再次被使用时,就可能导致不该分页的方法去消费这个分页参数,这就产生了莫名其妙的分页。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章