Mybatis3.5.4源码分析-3- 获取mapper,反射调用查询

 BlogMapper mapper = session.getMapper(BlogMapper.class);

mybatis中,通过session.getMapper来获取mapper接口的实现类,同样的,ctrl+alt+B 进入这个方法的默认实现
org.apache.ibatis.session.defaults.DefaultSqlSession#getMapper 中:

  @Override
  public <T> T getMapper(Class<T> type) {
    
    
    return configuration.getMapper(type, this);
  }

它的实现是从全局配置类中获取mapper接口的实现:
org.apache.ibatis.session.Configuration#getMapper , 在前面的分析中,我们知道了knownMappers 保存的是mapper接口和MapperProxyFactory 之间的映射关系,因此这里先获取到了MapperProxyFactory这个工厂类,然后通过JDK动态代理创建了mapper接口的实现类:

  @SuppressWarnings("unchecked")
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    
    
    // 每个接口都有一个工厂类
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
    
    
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
    
    
      // 反射创建代理对象,是mapper接口的实现(代理类)
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
    
    
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }

动态代理创建mapper对象的过程如下:

  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    
    
    // 参数1: 类加载器
    // 参数2: 被代理类实现的接口
    // 参数3: 实现了InvocationHandler接口的一个代理类,后面执行代理类的方法时,会走到mapperProxy的invoke方法里面!
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] {
    
     mapperInterface }, mapperProxy);
  }

  public T newInstance(SqlSession sqlSession) {
    
    
    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

总结一下getMapper所做的事情:
1、 通过getmapper 获取工厂类MapperProxyFactory
2、 通过 MapperProxyFactory创建了一个代理类对象
既然是动态代理,那么必然会有一个invoke方法,如下:

@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
    try {
    
    
      // 从Object类继承的toString  hashCode  equals getClass等方法无需走执行sql的流程
      if (Object.class.equals(method.getDeclaringClass())) {
    
    
        return method.invoke(this, args);
      } else {
    
    
        // 提升获取mapperMethod的效率,到mapperMathodInvoker(内部接口)的invoke
        // 普通方法会走到plainMethodInvoker的invoke
        return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
      }
    } catch (Throwable t) {
    
    
      throw ExceptionUtil.unwrapThrowable(t);
    }
  }
private MapperMethodInvoker cachedInvoker(Method method) throws Throwable {
    
    
    try {
    
    
      // java8中的map方法,根据key获取值,如果值是null,则把后面Object的值
      // 赋给key,如果获取不到,就创建,
      // 虎丘的是mapperMethdoInvoker接口对象,只有一个invoke方法
      return methodCache.computeIfAbsent(method, m -> {
    
    
        if (m.isDefault()) {
    
    
          // 接口的默认方法(java8)只要实现接口,都会继承接口的默认方法,例如List.sort()
          try {
    
    
            if (privateLookupInMethod == null) {
    
    
              return new DefaultMethodInvoker(getMethodHandleJava8(method));
            } else {
    
    
              return new DefaultMethodInvoker(getMethodHandleJava9(method));
            }
          } catch (IllegalAccessException | InstantiationException | InvocationTargetException
              | NoSuchMethodException e) {
    
    
            throw new RuntimeException(e);
          }
        } else {
    
    
         // 普通方法返回PlainMethodInvoker
          return new PlainMethodInvoker(new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
        }
      });
    } catch (RuntimeException re) {
    
    
      Throwable cause = re.getCause();
      throw cause == null ? re : cause;
    }
  }

上面MapperMethod有两个属性,

  private final SqlCommand command;
  private final MethodSignature method;

SqlCommand 封装了statement id(如com.test.mapper.BolgMapper.selectBolgById) 和sql类型,MethodSignature 封装了返回值的类型;不管是DefaultMethodInvoker还是PlainMethodInvoker ,最终执行的invoke方法都是下面的这个方法:

   @Override
    public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
    
    
      // sql执行的真正起点
      return mapperMethod.execute(sqlSession, args);
    }

进入execute方法:

public Object execute(SqlSession sqlSession, Object[] args) {
    
    
    Object result;
    switch (command.getType()) {
    
    
      case INSERT: {
    
    
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.insert(command.getName(), param));
        break;
      }
      case UPDATE: {
    
    
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.update(command.getName(), param));
        break;
      }
      case DELETE: {
    
    
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.delete(command.getName(), param));
        break;
      }
      case SELECT:
        if (method.returnsVoid() && method.hasResultHandler()) {
    
    
          executeWithResultHandler(sqlSession, args);
          result = null;
        } else if (method.returnsMany()) {
    
    
          result = executeForMany(sqlSession, args);
        } else if (method.returnsMap()) {
    
    
          result = executeForMap(sqlSession, args);
        } else if (method.returnsCursor()) {
    
    
          result = executeForCursor(sqlSession, args);
        } else {
    
    
          Object param = method.convertArgsToSqlCommandParam(args);
          // 普通select 语句的执行入口
          result = sqlSession.selectOne(command.getName(), param);
          if (method.returnsOptional()
              && (result == null || !method.getReturnType().equals(result.getClass()))) {
    
    
            result = Optional.ofNullable(result);
          }
        }
        break;
      case FLUSH:
        result = sqlSession.flushStatements();
        break;
      default:
        throw new BindingException("Unknown execution method for: " + command.getName());
    }
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
    
    
      throw new BindingException("Mapper method '" + command.getName()
          + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    }
    return result;
  }

请注意上面 result = sqlSession.selectOne(command.getName(), param); 这里默认调用DefaultSqlSession的selectOne方法,它内部是通过selectList方法实现的:

 @Override
  public <T> T selectOne(String statement) {
    
    
    return this.selectOne(statement, null);
  }

  @Override
  public <T> T selectOne(String statement, Object parameter) {
    
    
    // Popular vote was to return null on 0 results and throw exception on too many.
    List<T> list = this.selectList(statement, parameter);
    if (list.size() == 1) {
    
    
      return list.get(0);
    } else if (list.size() > 1) {
    
    
      throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
    } else {
    
    
      return null;
    }
  }

selectList内部调用了重载的三个入参的selectList方法:

 @Override
  public <E> List<E> selectList(String statement, Object parameter) {
    
    
    // 为了体用多种重载和默认值,
    // 让参数少的调用参数多的方法,只实现一次!!!
    return this.selectList(statement, parameter, RowBounds.DEFAULT);
  }

  @Override
  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    
    
    try {
    
    
      // MappedStatement封装了所有增删改查标签
      MappedStatement ms = configuration.getMappedStatement(statement);
      // 如果cacheEnabled=true(默认) ,executor会被cachingExecutor装饰
      // executor是DefaultSqlSession的一个属性,在创建DefaultSqlSession的时候,就对它进行了赋值
      return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
    } catch (Exception e) {
    
    
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
    
    
      ErrorContext.instance().reset();
    }
  }

到了executor.query方法,由于二级缓存是默认打开的,它会先执行cachingExecutor中的方法,然后才是BaseExecutor中的方法:
在这里插入图片描述
org.apache.ibatis.executor.CachingExecutor#query(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.session.ResultHandler) 如下:

  @Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    
    
    // 获取sql语句
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    // 创建cachekey: 什么样的sql才是同一条sql?(同一个查询)
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

获取到sql之后,先去创建了一个cachekey,然后调用query方法:

@Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    
    
    // Cache对象在哪里创建的
    Cache cache = ms.getCache();
    // cache是否为null 由<cache>标签决定,如果没有配cache标签,不走二级缓存
    if (cache != null) {
    
    
      // flushCa=true 即使配置了cache标签,也会清空一级二级缓存
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
    
    
        ensureNoOutParams(ms, boundSql);
        @SuppressWarnings("unchecked")
          // 获取二级缓存
          // 缓存通过TransactionalCacheManager, TransactionalCache管理
          // 疑问:为什么要把二级缓存放到tcm —— 防止回滚后数据库没有数据,但是缓存了内容,
          // 因此要将二级缓存与事务绑定,当事务提交成功才将数据写入缓存;一级缓存是会话级别,事务发生回滚,会话关闭,缓存也就不存在了
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
    
    
          // 真正的执行器对象BaseExecutor的查询
          list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          // 写入二级缓存,这里并不是直接写入缓存,而是添加到一个entriesToAddOnCommit中
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    // 走到 SimpleExecutor  / ReuseExecutor / BatchExecutor
    return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); 才是真正进入BaseExecutor中去查询:

@Override
  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    
    
    // 异常体系:ErrorContext
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    if (closed) {
    
    
      throw new ExecutorException("Executor was closed.");
    }
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
    
    
      // flushCache=true时,即使是查询,也清空一级缓存
      clearLocalCache();
    }
    List<E> list;
    try {
    
    
      // 防止递归查询时重复处理缓存
      queryStack++;
      // 查询一级缓存
      // 问题:ResultHandler ResultSetHandler的区别
      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
      if (list != null) {
    
    
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
    
    
        // 真正的查询数据库的流程
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
    
    
      queryStack--;
    }
    if (queryStack == 0) {
    
    
      for (DeferredLoad deferredLoad : deferredLoads) {
    
    
        deferredLoad.load();
      }
      // issue #601
      deferredLoads.clear();
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
    
    
        // issue #482
        clearLocalCache();
      }
    }
    return list;
  }

list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql); 才是真正查询数据库了,我们知道mybatis默认是使用simpleExecutor执行器,
在这里插入图片描述
SimpleExecutor的doQuery方法就是核心操作了,在这个方法里面,创建了StatementHandler 对象,并执行了查询

  @Override
  public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    
    
    Statement stmt = null;
    try {
    
    
      Configuration configuration = ms.getConfiguration();
      // 关键对象StatementHandler ,这里处理后返回StatementHandler的具体实现: RoutingStatementHandler
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      // 获取一个Statement对象
      stmt = prepareStatement(handler, ms.getStatementLog());
      // 执行查询,RoutingStatementHandler的query()方法    
      // 这里的query方法,都是通过委托给RoutingStatementHandler去处理的;
      return handler.query(stmt, resultHandler);
    } finally {
    
    
      // 调用完成关闭stmt
      closeStatement(stmt);
    }
  }

关键点: StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql); 在创建StatementHandler 的过程中,又做了哪些事情呢?

 public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    
    
    // 任意操作,都先做一个路由的操作 RoutingStatementHandler
    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
    // 植入插件逻辑(返回代理对象)
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
  }

查看RoutingStatementHandler这个构造函数:


  public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    
    
    // StatementType哪里来的?  是增删改查标签中的statementType="PREPARED" ,默认值是PREPARED
    switch (ms.getStatementType()) {
    
    
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        // PreparedStatementHandler的时候做了什么
        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case CALLABLE:
        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      default:
        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
    }

  }

继续看PreparedStatementHandler 创建过程中做了什么操作:

  public PreparedStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    
    
    super(executor, mappedStatement, parameter, rowBounds, resultHandler, boundSql);
  }

调用父类的构造,创建了四大对象中的parameterHandler和resultSetHandler

  protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    
    
    this.configuration = mappedStatement.getConfiguration();
    this.executor = executor;
    this.mappedStatement = mappedStatement;
    this.rowBounds = rowBounds;

    this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
    this.objectFactory = configuration.getObjectFactory();

    if (boundSql == null) {
    
     // issue #435, get the key before calculating the statement
      generateKeys(parameterObject);
      boundSql = mappedStatement.getBoundSql(parameterObject);
    }

    this.boundSql = boundSql;
    // 创建了四大对象中的parameterHandler和resultSetHandler,到这里,插件可以拦截的四大对象(还有Executor,StatementHandler)都创建了
    this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);
    this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);
  }

并且在创建parameterHandler和resultSetHandler 对象的时候,植入了插件的逻辑:

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

此时的执行流程如下图所示:
在这里插入图片描述
1.解析配置文件,创建Configuration对象,把每一个sql语句变成了一个MappedStatement对象,把mapper接口跟MappreProxyFactory进行映射
2. 创建会话,得到SimpelExecutor,这里可能会经过装饰以及插件包装,然后创建事务,返回DefaultSqlSession
3. getMapper 拿到MappreProxyFactory,获取MappreProxy,创建mapper接口的代理对象,执行invoke方法

再返回到org.apache.ibatis.executor.SimpleExecutor#doQuery 方法中, stmt = prepareStatement(handler, ms.getStatementLog()); 获取了一个PrepareStatement对象(JDBC的原生对象),是调用SimpleExecutor的方法:

 private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    
    
    Statement stmt;
    Connection connection = getConnection(statementLog);
    stmt = handler.prepare(connection, transaction.getTimeout());
    handler.parameterize(stmt);
    return stmt;
  }

然后执行query方法,先进入RoutingStatementHandler的query()

  @Override
  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    
    
    return delegate.query(statement, resultHandler);
  }

然后才进入PrepareStatement的查询方法,()

  @Override
  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    
    
    PreparedStatement ps = (PreparedStatement) statement;
    ps.execute();
    return resultSetHandler.handleResultSets(ps);
  }

下面都是JDBC的代码了:

  @Override
  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    
    
    PreparedStatement ps = (PreparedStatement) statement;
    // JDBC原生流程
    ps.execute();
    // 处理结果集,如果有插件代理ResultSetHandler,会先走到被拦截的业务逻辑
    return resultSetHandler.handleResultSets(ps);
  }

猜你喜欢

转载自blog.csdn.net/weixin_41300437/article/details/108592104
今日推荐