自定义mybatis拦截器实现分页

原理:

mybatis提供了拦截器功能,我们可以对Executor,StatementHandler,ParameterHandler,ResultSetHandler进行拦截,也就是代理。

实现:

分页需要提供两个数据,一是偏移量,行数。在mysql数据库中我们通过limit offset,rows实现分页。
返回的结果,我们需要总数,总页数,当前页数,结果集来映射我们的前端显示。
我们通过拦截Executor来实现,并且制定拦截的方法是query方法。

  1. 第一步:区分出分页方法,怎么实现在不改变任何代码的情况下将分页区别出来,首先,我们肯定需要知道哪些方法是分页,我们通过定义统一的方法后缀名来区分。
  2. 第二步:查询出总数,我们需要在原来sql的基础上查询出总数是多少,在这里我们通过映射对象,调用Executor的query方法来获得。
  3. 第三步:改造sql,变成分页的sql语句。
  4. 第四步:执行语句。
    在这里有些地方并没有提供直接的修改方法,所以只能通过替换的形式,代码冗余。
原理理解

在这其中有几个关键的类

  1. MappedStatement
  2. BoundSql
  3. Executor
MappedStatement

这个就是我们mapper文件中对应的一个select/update/delete节点。

public final class MappedStatement {
   private String resource;//mapper配置文件名,如:UserMapper.xml
   private Configuration configuration;//全局配置
   private String id;//节点的id属性加命名空间,如:com.lucky.mybatis.dao.UserMapper.selectByExample
   private Integer fetchSize;
   private Integer timeout;//超时时间
   private StatementType statementType;//操作SQL的对象的类型
   private ResultSetType resultSetType;//结果类型
   private SqlSource sqlSource;//sql语句
   private Cache cache;//缓存
   private ParameterMap parameterMap;
   private List<ResultMap> resultMaps;
   private boolean flushCacheRequired;
   private boolean useCache;//是否使用缓存,默认为true
   private boolean resultOrdered;//结果是否排序
   private SqlCommandType sqlCommandType;//sql语句的类型,如select、update、delete、insert
   private KeyGenerator keyGenerator;
   private String[] keyProperties;
   private String[] keyColumns;
   private boolean hasNestedResultMaps;
   private String databaseId;//数据库ID
   private Log statementLog;
   private LanguageDriver lang;
   private String[] resultSets;

通过mapperStatement我们可以获得sql,方法名,参数,结果类型,这些都是我们后面需要用到的。

BoundSql

BoundSql保存了sql执行sql语句所需要的所有参数,sql语句,传入的参数

public class BoundSql {

  private final String sql;
  private final List<ParameterMapping> parameterMappings;
  private final Object parameterObject;
  private final Map<String, Object> additionalParameters;
  private final MetaObject metaParameters;
Executor

执行器,所有的语句都通过这个执行器执行。我们下面主要的拦截对象,下面是我们要拦截的方法。

 <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey cacheKey, BoundSql boundSql) throws SQLException;

  <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException;
思路

有了上面的对象,我们也可以构建自己的查询,对于分页查询,我们说先需要获得总数量,这里我们需要在原有的基础上构建一个新的MappedStatement,修改sql和返回结果类型。对于分页查询,我们只需要在原来的基础上修改sql,但是MappedStatement并没哟支持直接修改sql的方法,我们只能构建新的MappedStatement替换原来的MappedStatement。

代码实现:

继承Interceptor接口。添加@Interceptor注解。在@Signature 注解中指定拦截的类型,方法,方法参数。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Intercepts {
    Signature[] value();
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Signature {
    Class<?> type();

    String method();

    Class<?>[] args();
}

实现接口的三个方法。

public class PageInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        return null;
    }

    @Override
    public Object plugin(Object o) {
        return null;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}

setProperties方法,有我们自定义提供方法的后缀,和页大小。

  public void setProperties(Properties properties)  {
        Integer o = Integer.valueOf((String) properties.get("pager.pageSize"));
        if(o==null){
            try {
                throw  new PageSizeNullException("pageSize can not be null");
            } catch (PageSizeNullException e) {
                e.printStackTrace();
            }
        }
        pageSize=o;
        String o1 = (String) properties.get("pager.pageFlag");
        if(o1==null){
            try {
                throw  new PageFlagNullException("pageFlag can not be null.");
            } catch (PageFlagNullException e) {
                e.printStackTrace();
            }
        }
        PAGE_FLAG=o1;

    }

intercept方法。参数Invocation,我们通过断点来看一下。target是Executor执行器,我们在args中可以获得MappedStatement映射对象,UserPager参数,RowBounds。


image.png

第一步:获得总数。

  /**
     * 构造count查询语句,创建新的boundSql,创建新的mappedStatement,再通过executor执行查询
     * @param executor
     * @param mappedStatement
     * @param parameter
     * @param boundSql
     * @param resultHandler
     * @return
     * @throws SQLException
     */
 public Long getTotalCount(Executor executor,MappedStatement mappedStatement,Object parameter,BoundSql boundSql,ResultHandler resultHandler) throws SQLException {
       String sql = boundSql.getSql();
        StringBuffer stringBuffer  = new StringBuffer();
        stringBuffer.append("select count(1) from (").append(sql).append(") as temp");
        BoundSql newboundSql = new BoundSql(mappedStatement.getConfiguration(),stringBuffer.toString(),boundSql.getParameterMappings(),parameter);
        MappedStatement mappedStatement1 = buildCountMappedStatement(mappedStatement, mappedStatement.getId()+COUNT_FLAG);
        CacheKey cacheKey = executor.createCacheKey(mappedStatement1, parameter, RowBounds.DEFAULT, boundSql);
        List query = executor.query(mappedStatement1, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, newboundSql);
        return (Long)query.get(0);
    }
 /**
     * 创建新的mappedStatement,添加结果映射
     * @param mappedStatement
     * @param id
     * @return
     */
    public MappedStatement buildCountMappedStatement(MappedStatement mappedStatement,String id){
            MappedStatement.Builder builder = new MappedStatement.Builder(mappedStatement.getConfiguration(),id,mappedStatement.getSqlSource(),mappedStatement.getSqlCommandType());

            List<ResultMap> resultMapList = new ArrayList<>();
            ResultMap.Builder resultMap =  new ResultMap.Builder(mappedStatement.getConfiguration(),id,Long.class,DEFAULT_LIST_RESULTMAPPING);
            resultMapList.add(resultMap.build());
            builder.resultMaps(resultMapList);
            return builder.build();
        }

获得总数之后,开始构建分页查询,我们只需要在原来的基础之上修改sql就行了,但是并没有可以直接修改sql的方法,所以我们只能通过替换mappedStatement的方式。mybatis提供了一个类似反射的工具MetaObject。

 /**
     * 利用mybatis提供的反射工具,将sql注入到mappedStatement中去
     * @param invocation
     * @param sql
     */
    public void resetSql2Invocation(Invocation invocation,String sql){
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatements = (MappedStatement) args[0];
        Object parameter= args[1];
        MappedStatement mappedStatement = buildMappedStatement(mappedStatements, mappedStatements.getBoundSql(parameter));
        MetaObject metaObject = MetaObject.forObject(mappedStatement, OBJECT_FACTORY, OBJECT_WRAPPER_FACTORY, REFLECTOR_FACTORY);
        metaObject.setValue("sqlSource.boundSql.sql",sql);
        args[0]=mappedStatement;
    }

    /**
     * 构建新的mappedStatement
     * @param mappedStatement
     * @param boundSql
     * @return
     */
    public MappedStatement buildMappedStatement(MappedStatement mappedStatement,BoundSql boundSql){
        MappedStatement.Builder builder = new MappedStatement.Builder(mappedStatement.getConfiguration(),mappedStatement.getId(),new BoundSqlSource(boundSql),mappedStatement.getSqlCommandType());
       setProperties(builder,mappedStatement);
        return builder.build();
    }

至此,完成了分页的实现,我们看一下结果。


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容