Mybatis Plugin解析

mybatis的插件有4个扩展点:

Executor:执行器

ParameterHandler:参数处理器

ResultSetHandler:结果集处理器

StatementHandler:Statement 处理器

它执行 interceptorChain.pluginAll(executor) 生成Jdk代理

  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
    parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
    return parameterHandler;
  }
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
      ResultHandler resultHandler, BoundSql boundSql) {
    ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
    resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
    return resultSetHandler;
  }
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
  }

我们手写一个把内存分页转为物理分页的插件。它拦截了

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

这个方法。

我们传入一个RowBounds 参数,接口是List<User> queryUser(RowBounds rowBounds);

@Intercepts({@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
@Component
public class ExamplePlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
		Object[] args = invocation.getArgs();
        RowBounds rowBounds = (RowBounds) args[2];
        args[2] = RowBounds.DEFAULT;
        MappedStatement mappedStatement = (MappedStatement) args[0];
        BoundSql boundSql = mappedStatement.getBoundSql(args[1]);
        String sql = boundSql.getSql();
        String limit = String.format("limit %d,%d", rowBounds.getOffset(), rowBounds.getLimit());
        sql = sql + " " + limit;
        SqlSource sqlSource = new StaticSqlSource(mappedStatement.getConfiguration(), sql, boundSql.getParameterMappings());
        Field field = MappedStatement.class.getDeclaredField("sqlSource");
        field.setAccessible(true);
        field.set(mappedStatement, sqlSource);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }
}

executor = (Executor) interceptorChain.pluginAll(executor);依次执行插件拦截器链的逻辑。拦截器链本质是一个链表,遍历链表一遍有两种模式,一种是使用一个List封装所有的拦截器,然后遍历这个List;另一种是一个拦截器里维护下一个拦截器引用的next,遍历的时候使用next去遍历。

public interface Interceptor {

  Object intercept(Invocation invocation) throws Throwable;

  default Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }

  default void setProperties(Properties properties) {
    // NOP
  }

}

我们插件的逻辑被放入代理中了,最后的target是代理

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;
  }

SqlSession会话开始执行后,Executor代理的方法被调用的时候插件的业务逻辑就被执行。

  @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);
    }
  }

先执行完拦截器,执行完拦截器后就进入到我们拦截的方法里了。

Executor里的query()方法,参数列表是( MappedStatement, Object, RowBounds, ResultHandler )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在您提供的引用中,出现了一个错误信息"Cannot resolve plugin org.mybatis.generator:mybatis-generator-maven-plugin:1.3.0"。这个错误通常表示Maven无法解析或找到所需的插件。根据您的引用内容,我可以提供以下解决方法: 1. 确保您的Maven配置文件中的依赖项正确配置。检查您的pom.xml文件中是否添加了正确的插件依赖以及其版本号。 2. 检查您的Maven仓库中是否存在所需的插件。您可以尝试删除Maven本地仓库中与该插件相关的文件,然后重新运行Maven命令,以便重新下载并安装插件。 3. 检查您的网络连接是否正常。有时候插件无法下载是由于网络问题导致的。您可以尝试使用其他网络或者使用代理进行连接。 4. 尝试使用更新的插件版本。您提供的引用中使用的是1.3.0版本的插件,尝试使用更高版本的插件,可能会解决该问题。 总结起来,要解决"Cannot resolve plugin org.mybatis.generator:mybatis-generator-maven-plugin:1.3.0"的问题,您可以检查Maven配置文件、Maven仓库、网络连接并尝试更新插件版本。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.6:generate (default-](https://blog.csdn.net/qq_52291182/article/details/121033304)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [Maven更新失败,Cannot resolve plugin org.apache.maven.plugins:maven-compiler-plugin:3.1](https://download.csdn.net/download/weixin_38687277/14888111)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值