mybatis自定义简单分页插件

在编写插件以前有必要介绍下mybatis里面plugin相关的类

在这里插入图片描述
从上往下

/**
 * 拦截器
 */
public interface Interceptor {

  /**
   * 拦截方法
   * @param invocation 封装代理类参数
   */
  Object intercept(Invocation invocation) throws Throwable;

  /**
   * 执行
   * @param target
   * @return
   */
  default Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }

  /**
   * 读取插件设置的参数列表
   * @param properties 参数列表
   */
  default void setProperties(Properties properties) {
    // NOP
  }

}
/**
 * @author Clinton Begin
 */
/**
 * 拦截器链
 */
public class InterceptorChain {

  /**
   * 拦截器集合
   */
  private final List<Interceptor> interceptors = new ArrayList<>();

  /**
   * 通过拦截器包装目标类
   */
  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }

  /**
   * 添加拦截器
   * @param interceptor
   */
  public void addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
  }

  /**
   *
   * @return 返回一个只读的拦截器集合
   */
  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }

}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts {
  /**
   * Returns method signatures to intercept.
   *
   * @return method signatures
   */
  /**
   * @return 返回要拦截的方法签名
   */
  Signature[] value();
}
/**
 * 封装了jdk动态代理需要的参数和一个执行方法
 */
public class Invocation {

  private final Object target;
  private final Method method;
  private final Object[] args;

  public Invocation(Object target, Method method, Object[] args) {
    this.target = target;
    this.method = method;
    this.args = args;
  }

  public Object getTarget() {
    return target;
  }

  public Method getMethod() {
    return method;
  }

  public Object[] getArgs() {
    return args;
  }

  public Object proceed() throws InvocationTargetException, IllegalAccessException {
    return method.invoke(target, args);
  }

}
/**
 * 插件类
 */
public class Plugin implements InvocationHandler {

  // 目标对象
  private final Object target;
  // 过滤器链
  private final Interceptor interceptor;
  // 签名map
  private final Map<Class<?>, Set<Method>> signatureMap;

  private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
    this.target = target;
    this.interceptor = interceptor;
    this.signatureMap = signatureMap;
  }

  /**
   * 包装方法,是否返回代理类的逻辑实现
   * @param target 目标对象
   * @param interceptor 过滤器链
   * @return 可能返回一个代理类(如果条件成立)
   */
  public static Object wrap(Object target, Interceptor interceptor) {
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

  /**
   * jdk动态代理的回调方法
   */
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
        return interceptor.intercept(new Invocation(target, method, args));
      }
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }

  /**
   * 返回注解上需要代理的类和方法
   */
  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
    }
    Signature[] sigs = interceptsAnnotation.value();
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
    for (Signature sig : sigs) {
      Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
      try {
        Method method = sig.type().getMethod(sig.method(), sig.args());
        methods.add(method);
      } catch (NoSuchMethodException e) {
        throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
      }
    }
    return signatureMap;
  }

  /**
   * 获取目标类实现注解上的目标类的所有接口
   */
  private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> interfaces = new HashSet<>();
    while (type != null) {
      for (Class<?> c : type.getInterfaces()) {
        if (signatureMap.containsKey(c)) {
          interfaces.add(c);
        }
      }
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[0]);
  }

}
/**
 * 指示方法签名的注释
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Signature {
  /**
   * 返回java类型。
   * @return
   */
  Class<?> type();

  /**
   * @return 返回方法名称
   */
  String method();

  /**
   * 
   * @return 返回方法参数的Java类型。
   */
  Class<?>[] args();
}

MyBatis 允许你在映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
ParameterHandler (getParameterObject, setParameters)
ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)
这些类中方法的细节可以通过查看每个方法的签名来发现,或者直接查看 MyBatis 发行包中的源代码。 如果你想做的不仅仅是监控方法的调用,那么你最好相当了解要重写的方法的行为。 因为在试图修改或重写已有方法的行为时,很可能会破坏 MyBatis 的核心模块。 这些都是更底层的类和方法,所以使用插件的时候要特别当心。

@Intercepts(
  {
    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
  }
)public class PageHelperPlugin implements Interceptor {

  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    Object[] args = invocation.getArgs();
    MappedStatement ms = (MappedStatement) args[0];
    Object parameter = args[1];
    RowBounds rowBounds = (RowBounds) args[2];
    ResultHandler resultHandler = (ResultHandler) args[3];
    Executor executor = (Executor) invocation.getTarget();
    BoundSql boundSql = ms.getBoundSql(parameter);
    CacheKey cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
    //拼接分页sql语句
    String sql = boundSql.getSql();
    String pageSql = sql + "\n LIMIT ?, ? ";
    //设置分页参数
    if (null == PAGE.get()){
      PAGE.set(defaultPage());
    }
    Map<String, Object> map = PAGE.get();
    //处理pageKey
    cacheKey.update(map.get(PAGE_NUM));
    cacheKey.update(map.get(PAGE_SIZE));
    //处理参数配置
    if (boundSql.getParameterMappings() != null) {
      List<ParameterMapping> newParameterMappings = new ArrayList<>(boundSql.getParameterMappings());
      newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGE_NUM, int.class).build());
      newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGE_SIZE, int.class).build());
      MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
      metaObject.setValue(PARAMETER_MAPPINGS, newParameterMappings);
    }
    BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(), map);
    return executor.query(ms, map, RowBounds.DEFAULT, resultHandler, cacheKey, pageBoundSql);
  }

  public static void startPage(int pageNum, int pageSize){
    Map<String, Object> map = new HashMap<String, Object>(2) {{
      put(PAGE_NUM, pageNum);
      put(PAGE_SIZE, pageSize);
    }};
    PAGE.set(map);
  }

  private Map<String, Object> defaultPage(){
    return new HashMap<String, Object>(2){{
      put(PAGE_NUM, 0);
      put(PAGE_SIZE, 10);
    }};
  }
}

测试代码

    PageHelperPlugin.startPage(0,2);
    List<User> users = userDao.selectByPage();
[User{id=4, name='zhu', age=1}, User{id=5, name='a', age=2}]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值