天天看點

MyBatis原理分析-深入淺出

真正掌握一個架構源碼分析是少不了的~

在講解整合Spring的原理之前了解原生的MyBatis執行原理是非常有必要的

MyBatis工作流程簡述 - 傳統工作模式

public static void main(String[] args) {
		InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = factory.openSession();
		String name = "tom";
		List<User> list = sqlSession.selectList("com.demo.mapper.UserMapper.getUserByName",params);
}

           

1、建立SqlSessionFactoryBuilder對象,調用build(inputstream)方法讀取并解析配置檔案,傳回SqlSessionFactory對象

2、由SqlSessionFactory建立SqlSession 對象,沒有手動設定的話事務預設開啟

3、調用SqlSession中的api,傳入Statement Id和參數,内部進行複雜的處理,最後調用jdbc執行SQL語句,封裝結果傳回。

MyBatis工作流程簡述 - 使用Mapper接口

由于面向接口程式設計的趨勢,MyBatis也實作了通過接口調用mapper配置檔案中的SQL語句

public static void main(String[] args) {
		//前三步都相同
		InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = factory.openSession();
		//這裡不再調用SqlSession 的api,而是獲得了接口對象,調用接口中的方法。
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		List<User> list = mapper.getUserByName("tom");
}

           

原生MyBatis原理分析

初始化工作

解析配置檔案

InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//這一行代碼正是初始化工作的開始。
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);

           

進入源碼分析:

// 1.我們最初調用的build
public SqlSessionFactory build(InputStream inputStream) {
	//調用了重載方法
    return build(inputStream, null, null);
  }

// 2.調用的重載方法
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      //  XMLConfigBuilder是專門解析mybatis的配置檔案的類
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      //這裡又調用了一個重載方法。parser.parse()的傳回值是Configuration對象
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } //省略部分代碼
  }

           

下面進入對配置檔案解析部分:

首先對Configuration對象進行介紹:

Configuration對象的結構和xml配置檔案的對象幾乎相同。

回顧一下xml中的配置标簽有哪些:

properties(屬性),settings(設定),typeAliases(類型别名),typeHandlers(類型處理器),objectFactory(對象工廠),mappers(映射器)等

Configuration也有對應的對象屬性來封裝它們:

(圖檔來自:https://blog.csdn.net/luanlouis/article/details/37744073)

MyBatis原理分析-深入淺出
也就是說,初始化配置檔案資訊的本質就是建立Configuration對象,将解析的xml資料封裝到Configuration内部的屬性中。
//在建立XMLConfigBuilder時,它的構造方法中解析器XPathParser已經讀取了配置檔案
//3. 進入XMLConfigBuilder 中的 parse()方法。
public Configuration parse() {
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    //parser是XPathParser解析器對象,讀取節點内資料,<configuration>是MyBatis配置檔案中的頂層标簽
    parseConfiguration(parser.evalNode("/configuration"));
    //最後傳回的是Configuration 對象
    return configuration;
}

//4. 進入parseConfiguration方法
//此方法中讀取了各個标簽内容并封裝到Configuration中的屬性中。
private void parseConfiguration(XNode root) {
    try {
      //issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      loadCustomVfs(settings);
      loadCustomLogImpl(settings);
      typeAliasesElement(root.evalNode("typeAliases"));
      pluginElement(root.evalNode("plugins"));
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      environmentsElement(root.evalNode("environments"));
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      typeHandlerElement(root.evalNode("typeHandlers"));
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
}


           

到此對xml配置檔案的解析就結束了(下文會對部分解析做詳細介紹),回到步驟 2. 中調用的重載build方法。

// 5. 調用的重載方法
public SqlSessionFactory build(Configuration config) {
	//建立了DefaultSqlSessionFactory對象,傳入Configuration對象。
    return new DefaultSqlSessionFactory(config);
  }

           

配置類方式

發散一下思路,既然解析xml是對Configuration中的屬性進行複制,那麼我們同樣可以在一個類中建立Configuration對象,手動設定其中屬性的值來達到配置的效果

執行SQL

先簡單介紹SqlSession:

SqlSession是一個接口,它有兩個實作類:DefaultSqlSession(預設)和SqlSessionManager(棄用,不做介紹)
MyBatis原理分析-深入淺出

SqlSession是MyBatis中用于和資料庫互動的頂層類,通常将它與ThreadLocal綁定,一個會話使用一個SqlSession,并且在使用完畢後需要close。

SqlSession中的兩個最重要的參數,configuration與初始化時的相同,Executor為執行器

MyBatis原理分析-深入淺出

Executor

Executor也是一個接口,他有三個常用的實作類BatchExecutor(重用語句并執行批量更新),ReuseExecutor(重用預處理語句prepared statements),SimpleExecutor(普通的執行器,預設)

MyBatis原理分析-深入淺出

SqlSession API方式

繼續分析,初始化完畢後,我們就要執行SQL了:

SqlSession sqlSession = factory.openSession();
		String name = "tom";
		List<User> list = sqlSession.selectList("com.demo.mapper.UserMapper.getUserByName",params);

           

獲得sqlSession

//6. 進入openSession方法。
  public SqlSession openSession() {
  	//getDefaultExecutorType()傳遞的是SimpleExecutor
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }

//7. 進入openSessionFromDataSource。
//ExecutorType 為Executor的類型,TransactionIsolationLevel為事務隔離級别,autoCommit是否開啟事務
//openSession的多個重載方法可以指定獲得的SeqSession的Executor類型和事務的處理
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      //根據參數建立指定類型的Executor
      final Executor executor = configuration.newExecutor(tx, execType);
      //傳回的是DefaultSqlSession
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }
           

執行sqlsession中的api

//8.進入selectList方法,多個重載方法。
public <E> List<E> selectList(String statement) {
    return this.selectList(statement, null);
}
public <E> List<E> selectList(String statement, Object parameter) {
    return this.selectList(statement, parameter, RowBounds.DEFAULT);
}

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      //根據傳入的全限定名+方法名從映射的Map中取出MappedStatement對象
      MappedStatement ms = configuration.getMappedStatement(statement);
      //調用Executor中的方法處理
      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();
    }
 }

           

介紹一下MappedStatement

  • 作用:MappedStatement與Mapper配置檔案中的一個select/update/insert/delete節點相對應。mapper中配置的标簽都被封裝到了此對象中,主要用途是描述一條SQL語句。
  • **初始化過程:**回顧剛開始介紹的加載配置檔案的過程中,會對mybatis-config.xml中的各個标簽都進行解析,其中有 mappers标簽用來引入mapper.xml檔案或者配置mapper接口的目錄
<select id="getUser" resultType="user" >
    select * from user where id=#{id}
  </select>
           

這樣的一個select标簽會在初始化配置檔案時被解析封裝成一個MappedStatement對象,然後存儲在Configuration對象的mappedStatements屬性中,mappedStatements 是一個HashMap,存儲時key = 全限定類名 + 方法名,value = 對應的MappedStatement對象。

  • 在configuration中對應的屬性為
Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection")

           
  • 在XMLConfigBuilder中的處理:
private void parseConfiguration(XNode root) {
    try {
      // 省略其他标簽的處理
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }

           

繼續源碼中的步驟,進入 executor.query()

//此方法在SimpleExecutor的父類BaseExecutor中實作
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
	//根據傳入的參數動态獲得SQL語句,最後傳回用BoundSql對象表示
    BoundSql boundSql = ms.getBoundSql(parameter);
    //為本次查詢建立緩存的Key
    CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
    return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
 }
 
//進入query的重載方法中
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    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()) {
      clearLocalCache();
    }
    List<E> list;
    try {
      queryStack++;
      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;
  }

//從資料庫查詢
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    List<E> list;
    localCache.putObject(key, EXECUTION_PLACEHOLDER);
    try {
      // 查詢的方法
      list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
    } finally {
      localCache.removeObject(key);
    }
    // 将查詢結果放入緩存
    localCache.putObject(key, list);
    if (ms.getStatementType() == StatementType.CALLABLE) {
      localOutputParameterCache.putObject(key, parameter);
    }
    return list;
  }

// 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();
      // 傳入參數建立StatementHanlder對象來執行查詢
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      // 建立jdbc中的statement對象
      stmt = prepareStatement(handler, ms.getStatementLog());
      // StatementHandler進行處理
      return handler.query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }

// 建立Statement的方法
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    //條代碼中的getConnection方法經過重重調用最後會調用openConnection方法,從連接配接池中獲得連接配接。
    Connection connection = getConnection(statementLog);
    stmt = handler.prepare(connection, transaction.getTimeout());
    handler.parameterize(stmt);
    return stmt;
  }
//從連接配接池獲得連接配接的方法
protected void openConnection() throws SQLException {
    if (log.isDebugEnabled()) {
      log.debug("Opening JDBC Connection");
    }
    //從連接配接池獲得連接配接
    connection = dataSource.getConnection();
    if (level != null) {
      connection.setTransactionIsolation(level.getLevel());
    }
    setDesiredAutoCommit(autoCommit);
  }


//進入StatementHandler進行處理的query,StatementHandler中預設的是PreparedStatementHandler
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    PreparedStatement ps = (PreparedStatement) statement;
    //原生jdbc的執行
    ps.execute();
    //處理結果傳回。
    return resultSetHandler.handleResultSets(ps);
  }

           

接口方式

回顧一下寫法:

public static void main(String[] args) {
		//前三步都相同
		InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = factory.openSession();
		
		//這裡不再調用SqlSession 的api,而是獲得了接口對象,調用接口中的方法。
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		List<User> list = mapper.getUserByName("tom");
}
           

思考一個問題,通常的Mapper接口我們都沒有實作的方法卻可以使用,是為什麼呢?答案很簡單 動态代理

開始之前介紹一下MyBatis初始化時對接口的處理:MapperRegistry是Configuration中的一個屬性,它内部維護一個HashMap用于存放mapper接口的工廠類,每個接口對應一個工廠類。mappers中可以配置接口的包路徑,或者某個具體的接口類。

<!-- 将包内的映射器接口實作全部注冊為映射器 -->
<mappers>
  <mapper class="com.demo.mapper.UserMapper"/>
  <package name="com.demo.mapper"/>
</mappers>

           
  • 當解析mappers标簽時,它會判斷解析到的是mapper配置檔案時,會再将對應配置檔案中的增删改查标簽一 一封裝成MappedStatement對象,存入mappedStatements中。(上文介紹了)
  • 當判斷解析到接口時,會建立此接口對應的MapperProxyFactory對象,存入HashMap中,key = 接口的位元組碼對象,value = 此接口對應的MapperProxyFactory對象。
//MapperRegistry類
public class MapperRegistry {
  private final Configuration config;
  //這個類中維護一個HashMap存放MapperProxyFactory
  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

  //解析到接口時添加接口工廠類的方法
  public <T> void addMapper(Class<T> type) {
    if (type.isInterface()) {
      if (hasMapper(type)) {
        throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
      }
      boolean loadCompleted = false;
      try {
        //重點在這行,以接口類的class對象為key,value為其對應的工廠對象,構造方法中指定了接口對象
        knownMappers.put(type, new MapperProxyFactory<>(type));
        // It's important that the type is added before the parser is run
        // otherwise the binding may automatically be attempted by the
        // mapper parser. If the type is already known, it won't try.
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        parser.parse();
        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }
}

           

正文:

進入sqlSession.getMapper(UserMapper.class)中

//DefaultSqlSession中的getMapper
public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
}

//configuration中的給getMapper
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
}

//MapperRegistry中的getMapper
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
	//從MapperRegistry中的HashMap中拿MapperProxyFactory
    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類中的newInstance方法
 public T newInstance(SqlSession sqlSession) {
 	// 建立了JDK動态代理的Handler類
    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    // 調用了重載方法
    return newInstance(mapperProxy);
  }

//MapperProxy類,實作了InvocationHandler接口
public class MapperProxy<T> implements InvocationHandler, Serializable {
  
  //省略部分源碼	

  private final SqlSession sqlSession;
  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache;
  
  // 構造,傳入了SqlSession,說明每個session中的代理對象的不同的!
  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }
  
  //省略部分源碼
}

//重載的方法,由動态代理建立新示例傳回。
protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
 }

           

在動态代理傳回了示例後,我們就可以直接調用mapper類中的方法了,說明在MapperProxy中的invoke方法中已經為我們實作了方法。

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //判斷調用是是不是Object中定義的方法,toString,hashCode這類非。是的話直接放行。
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    } 
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    // 重點在這:MapperMethod最終調用了執行的方法
    return mapperMethod.execute(sqlSession, args);
  }


public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    //判斷mapper中的方法類型,最終調用的還是SqlSession中的方法
    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);
          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;
  }

           

總結

使用接口方式也就是mybatis架構和傳統方式的差別也就是使用了動态代理-責任鍊模式進行了參數的轉換處理,最後還是調用傳統方式中的SQLsession中的api