【java框架ssm-mybatis】使用mybait自定义拦截器实现分页功能

使用mybatis插件实现分页功能


前言:前几天在公司发现公司框架一个好用的分页功能,使用查询的实体类继承一个分页类,并且在前端传入分页信息。mybatis执行的时候就会自动进行分页操作。遂自己研究了下,是利用了mybatis的自定义插件功能。今天实现了下,实现代码如下,具体讲解待日后补加

首先是项目结构图,就是简单的ssm项目分层
【java框架ssm-mybatis】使用mybait自定义拦截器实现分页功能
其中分页的关键类是utils包下的MybatisPluginPage.java和BasePage
首先看下关键代码
BasePage.java

package com.tff622.idea.ssm.utils;

import java.util.List;

public  class BasePage {
    private int pageSize = 5;
    private int pageNum = 1;//默认值
    private int totalNum;
    private int currentPage;
    private int totalPage;
    private List<?> list;
    public BasePage(){

    }
    public BasePage(int pageNum) {

        this.pageNum = pageNum;
    }
    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public List<?> getList() {
        return list;
    }

    public void setList(List<?> list) {
        this.list = list;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getTotalNum() {
        return totalNum;
    }

    public void setTotalNum(int totalNum) {
        this.totalNum = totalNum;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }
}

MybatisPluginPage.java

package com.tff622.idea.ssm.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Properties;

//@Intercepts({
//        @Signature(
//                type = ResultSetHandler.class,//这是指拦截哪个接口
//                method = "query", //这个接口内的哪个方法名,不要拼错了
//                args = {Statement.class})
//})
@Component
@Intercepts(@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class MybatisPluginPage implements Interceptor {


    public Object intercept(Invocation invocation) throws Throwable {
//        Object target = invocation.getTarget(); //被代理对象
//        Method method = invocation.getMethod(); //代理方法
        Object[] args = invocation.getArgs(); //方法参数
        // do something ...... 方法拦截前执行代码块
        final MappedStatement mappedStatement = (MappedStatement) args[0];//获取执行的时的sql
        Object resultType = args[1];//获取传参的对象

        int pageSize;
        int pageNum;
        if (args[1] != null && args[1] instanceof BasePage) {//判断是否resultType是否为BasePage对象的子类 如果是则获取分页信息
            BasePage pageMessage = (BasePage) resultType;
            pageSize = pageMessage.getPageSize();
            pageNum = pageMessage.getPageNum();
        }else{// 否则不进行分页
            return  invocation.proceed();
        }
        //获取要执行的sql信息
        BoundSql boundSql = mappedStatement.getBoundSql(resultType);
        String sql = "select * from (" + boundSql.getSql() + ")a limit " + (pageNum - 1) * pageSize + "," + (pageNum) * pageSize;//重新组织sql
        BoundSql newBoundsql = new BoundSql(mappedStatement.getConfiguration(), sql, boundSql.getParameterMappings(), resultType);//使用新的sql组建一个boundSql
        MappedStatement newMs = newMapperStatement(mappedStatement, new BoundsqlRource(newBoundsql));//使用新的boundSql组建一个MappedStatement
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                newBoundsql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
            }
        }
        invocation.getArgs()[0] = newMs;//将新的mappedStatement对象放入invocation中
        Object result = invocation.proceed();
        // do something .......方法拦截后执行代码块
        return result;
    }

    private MappedStatement newMapperStatement(MappedStatement ms, SqlSource newsql) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newsql, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(ms.getKeyProperties()[0]);
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();

    }

    class BoundsqlRource implements SqlSource {

        private BoundSql boundSql;

        public BoundsqlRource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }


    @Override
    public void setProperties(Properties properties) {

    }
}

写好上面俩个类之后,开始调用,首先在mybatis-config中注册自定义插件
【java框架ssm-mybatis】使用mybait自定义拦截器实现分页功能
然后在vo类中继承BasePage
【java框架ssm-mybatis】使用mybait自定义拦截器实现分页功能
最后在调用查询列表接口时传入vo类就可以了
【java框架ssm-mybatis】使用mybait自定义拦截器实现分页功能
最后我们看一下效果,mapper文件中是这样写的
【java框架ssm-mybatis】使用mybait自定义拦截器实现分页功能
经过我们添加了分页功能后,执行的sql就变成了这样。
【java框架ssm-mybatis】使用mybait自定义拦截器实现分页功能
到此分页功能实现完毕。
参考文章:
https://www.jianshu.com/p/0a72bb1f6a21
https://blog.csdn.net/qq_29034189/article/details/113624023

上一篇:MyBatis源码学习三:mybatis插件


下一篇:MyBatis查询的意外问题 <if>标签 ==和=的区别