MyBatis-一次選擇查詢過程


1初步:

MyBatis初始化完後,org.apache.ibatis.session.Configuration中,會有已經初始化完的數據,供後續的執行:

1.1 mapperRegistry

MapperRegistry的實例,有一個屬性Map<Class<?>, MapperProxyFactory<?>> knownMappers

  • 密鑰:Mapper類,某種接口'com.xxx.yyy.model.UserMapper';
  • 值:MapperProxyFactory對象,是Mapper代理類MapperProxy的工廠,創建MapperProxy對象執行Mapper類中定義的方法。

1.2 mappingStatement

類型是Map<String, MappedStatement>

  • key:MappedStatement對象的id,如'com.xxx.yyy.model.UserMapper.selectList';
  • 值:MappedStatement對象。

2查詢過程

MyBatis分三個步驟執行查詢過程:

  • 1創建SqlSession,默認實現類是DefaultSqlSession
  • 1獲取Mapper,如session.getMapper(UserMapper.class);
  • 2用Mapper執行查詢,如userMapper.findList()

2.1創建SqlSession

DefaultSqlSessionFactory.openSession

  public SqlSession openSession(boolean autoCommit) {
    // 第一步
    // Configuration中:defaultExecutorType = ExecutorType.SIMPLE
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, autoCommit);
  }
  
    // 第二步
    //openSessionFromDataSource關鍵代碼:
    final Executor executor = configuration.newExecutor(tx, execType);
    return new DefaultSqlSession(configuration, executor, autoCommit);
複製代碼

執行者從Configuration.newExecutor方法中創建:

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;
  }
複製代碼

newExecutor的執行過程如下:

  • 根據不同的ExecutorType返回不同​​Executor;
  • 因配置中默認爲ExecutorType.SIMPLE,所以默認使用SimpleExecutor
  • 如果開啓了緩存,則返回CachingExecutor對象;
  • 通過interceptorChain.pluginAll加入攔截器Interceptor列表。

2.2獲取映射器

DefaultSqlSessionConfiguration.mapperRegistry中映射電子雜誌的實現對象:

// 第一步
// DefaultSqlSesison:
 public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
  }

// 第二步
// Configuration:
 public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }
  
// 第三步
// MapperRegistry:
// 從屬性knownMappers中獲取MapperProxyFactory對象,獲取到後執行newInstance獲取MapperProxy,即Mapper類的實現對象。
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 {
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }
  
 // 第四步
 // MapperProxyFactory 創建MapperProxy對象
   protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

複製代碼

由上面的MapperProxyFactory代碼可知,每次執行session.getMapper都會創建MapperProxy對象及其代理對象,因此應避免多次調用session.getMapper

2.3執行查詢

MyBatis使用JDK代理方式,MapperProxy實現了InvocationHandler接口,所以Mapper接口類的實現方法,是在MapperProxy.invoke方法裏執行。

invoke中,獲取或創建一個MapperMethod對象,然後執行MapperMethod.execute方法。

//// 獲取MapperMethod對象
  private MapperMethod cachedMapperMethod(Method method) {
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }
  
//// 執行execute
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
複製代碼

2.3.1 MapperMethod創建

MapperMethod有兩個屬性:

  private final SqlCommand command;
  private final MethodSignature method;
複製代碼

1)SqlCommand

SqlCommand有兩個屬性:

  • 字符串名稱:MappedStatement的id;
  • SqlCommandType類型:MappedStatement的sqlCommandType,UNKNOWN,INSERT,UPDATE,DELETE,SELECT,FLUSH。

SqlCommand創建時,會從配置中獲取MappedStatement對象,獲取到應使用的名稱和類型的賦值:

String statementId = mapperInterface.getName() + "." + methodName;

if (configuration.hasStatement(statementId)) {
    return configuration.getMappedStatement(statementId);
}
複製代碼

2)方法簽名

    private final boolean returnsMany; // configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray()
    private final boolean returnsMap; // 
    private final boolean returnsVoid; // void.class.equals(this.returnType)
    private final boolean returnsCursor; // org.apache.ibatis.cursor.Cursor.class.equals(this.returnType)
    private final Class<?> returnType;
    //////
    private final ParamNameResolver paramNameResolver; //  new ParamNameResolver(configuration, method)
複製代碼

2.3.2 MapperMethod.execute

根據command.type,判斷執行的操作:

 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);
          result = sqlSession.selectOne(command.getName(), param);
        }
        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;
  }
複製代碼

在執行調用的executeFor*方法中,最終調用的是sqlSession.select*方法。

2.3.3 session.selectList

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      // 第一步,從Configuration中取出MappedStatement對象
      // statement : interfaceName + "." + methodName
      MappedStatement ms = configuration.getMappedStatement(statement);
      
      // 第二步,執行查詢
      // executor : 前面Configuration.newExecutor創建的executor,默認SimpleExecutor
      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的調用鏈:

BaseExecutor.query-> BaseExecutor.queryFromDatabase-> SimpleExecutor.doQuery

SimpleExecutor.doQuery:

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();
      
      // 第一步 創建RoutingStatementHandler
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      
      // 第二步 調用StatementHandler.prepare創建Statement
      stmt = prepareStatement(handler, ms.getStatementLog());
      
      // 第三步 執行StatementHandler.query
      return handler.<E>query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }
複製代碼

2.3.4 StatementHandler

1)RoutingStatementHandler

configuration.newStatementHandler中創建的是RoutingStatementHandler,然後設置攔截器:

  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;
  }
複製代碼

RoutingStatementHandler是一種委派模式,根據MappedStatement.statementType的不同,返回不同的StatementHandler實現類:

  // 代理
  private final StatementHandler delegate;
  public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    switch (ms.getStatementType()) {
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        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());
    }
  }
複製代碼

2)StatementHandler.prepare

創建java.sql.Statement對象,調用鏈:

RoutingStatementHandler.prepare-> BaseStatementHandler.prepare-> PreparedStatementHandler.instantiateStatement

instantiateStatementBaseStatementHandler的抽象方法,供子類實現。

  // PreparedStatementHandler
  protected Statement instantiateStatement(Connection connection) throws SQLException {
    if (mappedStatement.getResultSetType() != null) {
      return connection.createStatement(mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY);
    } else {
      return connection.createStatement();
    }
  }
複製代碼

3)StatementHandler.query

有了Statement之後,就可以拿來進行查詢了:

  @Override
  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    PreparedStatement ps = (PreparedStatement) statement;
    ps.execute();
    return resultSetHandler.<E> handleResultSets(ps);
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章