深入Mybatis源碼——執行流程

来源:https://www.cnblogs.com/yewy/archive/2020/07/07/13263817.html
-Advertisement-
Play Games

前言 上一篇分析Mybatis是如何載入解析XML文件的,本篇緊接上文,分析Mybatis的剩餘兩個階段:代理封裝和SQL執行。 正文 代理封裝 Mybatis有兩種方式調用Mapper介面: private static SqlSessionFactory sqlMapper = new SqlS ...


前言

上一篇分析Mybatis是如何載入解析XML文件的,本篇緊接上文,分析Mybatis的剩餘兩個階段:代理封裝SQL執行

正文

代理封裝

Mybatis有兩種方式調用Mapper介面:

private static SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);

// 第一種
try (SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE)) {
  Blog blog = session.selectOne("org.apache.ibatis.domain.blog.mappers.BlogMapper.selectBlogWithPostsUsingSubSelect", 1);
}

// 第二種
try (SqlSession session = sqlMapper.openSession()) {
  AuthorMapper mapper = session.getMapper(AuthorMapper.class);
  Author author = mapper.selectAuthor(101);
}

從上面代碼可以看到無論是哪一種首先都要創建SqlSessionFactory對象,然後通過這個對象拿到SqlSession對象。在早期版本中只能通過該對象的增刪改調用Mapper介面,很明顯這種方式可讀性很差,難以維護,寫起來也複雜,所以後面谷歌開始維護Mybatis後,重新封裝提供了第二種方式直接調用Mapper介面。不過本質上第二種是在第一種的基礎之上實現的,所以下麵就以第二種為主進行分析,進入到getMapper方法:

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

  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }

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

mapperRegistry對象在上一篇分析過,是在解析xml中的mapper節點時註冊進去的,而這個對象中緩存了Mapper介面和對應的代理工廠的映射,所以getMapper的核心就是通過這個工廠去創建代理對象:

  public T newInstance(SqlSession sqlSession) {
	 //每次調用都會創建新的MapperProxy對象
    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

然後通過Mapper介面調用時首先就會調用到MapperProxyinvoke方法:

  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {//如果是Object本身的方法不增強
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    //從緩存中獲取mapperMethod對象,如果緩存中沒有,則創建一個,並添加到緩存中
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //調用execute方法執行sql
    return mapperMethod.execute(sqlSession, args);
  }

  private MapperMethod cachedMapperMethod(Method method) {
    return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
  }

首先從緩存中拿到MapperMethod對象,這個對象封裝了SQL語句的類型、命名空間、入參、返回類型等信息,然後通過它的execute方法調用SqlSession的增刪查改方法:

  public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    //根據sql語句類型以及介面返回的參數選擇調用不同的
    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()) {//返回值為void
          executeWithResultHandler(sqlSession, args);
          result = null;
        } else if (method.returnsMany()) {//返回值為集合或者數組
          result = executeForMany(sqlSession, args);
        } else if (method.returnsMap()) {//返回值為map
          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 = OptionalUtil.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;
  }

上文說過SqlSession本質上是門面模式的體現,其本質上是通過Executor執行器組件實現的,在該組件中定義了所有訪問資料庫的方法:

  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      //從configuration中獲取要執行的sql語句的配置信息
      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();
    }
  }

Executor對象是在獲取SqlSession時創建的:

  public SqlSession openSession() {
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }

  private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
    	//獲取mybatis配置文件中的environment對象
      final Environment environment = configuration.getEnvironment();
      //從environment獲取transactionFactory對象
      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();
    }
  }

TransactionFactory是我們在xml中配置的transactionManager屬性,可選的屬性有JDBC和Managed,然後根據我們的配置創建事務對象,之後才是創建Executor對象。

  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);
    }
    //如果有<cache>節點,通過裝飾器,添加二級緩存的能力
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    //通過interceptorChain遍歷所有的插件為executor增強,添加插件的功能
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

Executor有三個基本的實現類:

  • BatchExecutor:批處理執行器,執行批量更新、插入等操作。
  • ReuseExecutor:可重用執行器,緩存並重用Statement(Statement、PreparedStatement、CallableStatement)。
  • SimpleExecutor:預設使用的執行器,每次執行都會創建 新的Statement

這三個執行器都繼承了自抽象的BaseExecutor,同時如果開啟了二級緩存功能,在這裡還會裝飾一個CachingExecutor為其添加二級緩存的能力。另外還要註意在這段代碼的最後還有攔截器進行了包裝,也就是擴展插件的實現 ,關於這部分內容在一篇進行分析。

SQL執行

二級緩存的代碼很簡單,這裡直接略過,所以直接進入到BaseExecutor.query方法:

  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
	//獲取sql語句信息,包括占位符,參數等信息
    BoundSql boundSql = ms.getBoundSql(parameter);
    //拼裝緩存的key值
    CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
    return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
 }

  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) {//檢查當前executor是否關閉
      throw new ExecutorException("Executor was closed.");
    }
    if (queryStack == 0 && ms.isFlushCacheRequired()) {//非嵌套查詢,並且FlushCache配置為true,則需要清空一級緩存
      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) {//如果當前sql的一級緩存配置為STATEMENT,查詢完既清空一集緩存
        // issue #482
        clearLocalCache();
      }
    }
    return list;
  }

首先從一級緩存localCache裡面拿,如果沒有,才真正地訪問資料庫,並將返回結果存入到一級緩存中。

  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 {
      //調用抽象方法doQuery,方法查詢資料庫並返回結果,可選的實現包括:simple、reuse、batch
      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;
  }

這裡的doQuery是子類實現的,即模板模式,以SimpleExecutor為例:

  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();//獲取configuration對象
      //創建StatementHandler對象,
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      //StatementHandler對象創建stmt,並使用parameterHandler對占位符進行處理
      stmt = prepareStatement(handler, ms.getStatementLog());
      //通過statementHandler對象調用ResultSetHandler將結果集轉化為指定對象返回
      return handler.<E>query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }

通讀這裡的代碼我們可以發現,Executor本身是不會訪問到資料庫,而是作為指揮官,指揮三個小弟幹事:

  • StatementHandler:創建PreparedStatementStatementCallableStatement對象。
  • ParameterHandler:在StatementHandler構造函數中創建,對預編譯的 SQL 語句進行參數設置。
  • ResultSetHandler:在StatementHandler構造函數中創建,對資料庫返回的結果集(ResultSet)進行封裝,返回用戶指定的實體類型。

上面三個對象都是在configuration.newStatementHandler方法中創建的,然後調用prepareStatement拿到合適的Statement,如果是預編譯的還會進行參數設置:

  private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    //獲取connection對象的動態代理,添加日誌能力;
    Connection connection = getConnection(statementLog);
    //通過不同的StatementHandler,利用connection創建(prepare)Statement
    stmt = handler.prepare(connection, transaction.getTimeout());
    //使用parameterHandler處理占位符
    handler.parameterize(stmt);
    return stmt;
  }

如果在DEBUG模式下拿到的Connection對象是ConnectionLogger,這就和第一篇的內容串聯起來了。之後再通過query方法調用execute執行SQL語句,並使用ResultSetHandler處理結果集:

  public List<Object> handleResultSets(Statement stmt) throws SQLException {
    ErrorContext.instance().activity("handling results").object(mappedStatement.getId());
    //用於保存結果集對象
    final List<Object> multipleResults = new ArrayList<>();

    int resultSetCount = 0;
    //statment可能返回多個結果集對象,這裡先取出第一個結果集
    ResultSetWrapper rsw = getFirstResultSet(stmt);
    //獲取結果集對應resultMap,本質就是獲取欄位與java屬性的映射規則
    List<ResultMap> resultMaps = mappedStatement.getResultMaps();
    int resultMapCount = resultMaps.size();
    validateResultMapsCount(rsw, resultMapCount);//結果集和resultMap不能為空,為空拋出異常
    while (rsw != null && resultMapCount > resultSetCount) {
     //獲取當前結果集對應的resultMap
      ResultMap resultMap = resultMaps.get(resultSetCount);
      //根據映射規則(resultMap)對結果集進行轉化,轉換成目標對象以後放入multipleResults中
      handleResultSet(rsw, resultMap, multipleResults, null);
      rsw = getNextResultSet(stmt);//獲取下一個結果集
      cleanUpAfterHandlingResultSet();//清空nestedResultObjects對象
      resultSetCount++;
    }
    //獲取多結果集。多結果集一般出現在存儲過程的執行,存儲過程返回多個resultset,
    //mappedStatement.resultSets屬性列出多個結果集的名稱,用逗號分割;
    //多結果集的處理不是重點,暫時不分析
    String[] resultSets = mappedStatement.getResultSets();
    if (resultSets != null) {
      while (rsw != null && resultSetCount < resultSets.length) {
        ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);
        if (parentMapping != null) {
          String nestedResultMapId = parentMapping.getNestedResultMapId();
          ResultMap resultMap = configuration.getResultMap(nestedResultMapId);
          handleResultSet(rsw, resultMap, null, parentMapping);
        }
        rsw = getNextResultSet(stmt);
        cleanUpAfterHandlingResultSet();
        resultSetCount++;
      }
    }

    return collapseSingleResultList(multipleResults);
  }

這裡最終就是通過反射模塊以及Configuration類中的result相關配置進行結果映射:

  private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException {
    try {
      if (parentMapping != null) {//處理多結果集的嵌套映射
        handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
      } else {
        if (resultHandler == null) {//如果resultHandler為空,實例化一個人預設的resultHandler
          DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
          //對ResultSet進行映射,映射結果暫存在resultHandler中
          handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
          //將暫存在resultHandler中的映射結果,填充到multipleResults
          multipleResults.add(defaultResultHandler.getResultList());
        } else {
          //使用指定的rusultHandler進行轉換
          handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
        }
      }
    } finally {
      // issue #228 (close resultsets)
      //調用resultset.close()關閉結果集
      closeResultSet(rsw.getResultSet());
    }
  }

  public void handleRowValues(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
    if (resultMap.hasNestedResultMaps()) {//處理有嵌套resultmap的情況
      ensureNoRowBounds();
      checkResultHandler();
      handleRowValuesForNestedResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
    } else {//處理沒有嵌套resultmap的情況
      handleRowValuesForSimpleResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
    }
  }

  private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping)
      throws SQLException {
	//創建結果上下文,所謂的上下文就是專門在迴圈中緩存結果對象的
    DefaultResultContext<Object> resultContext = new DefaultResultContext<>();
    //1.根據分頁信息,定位到指定的記錄
    skipRows(rsw.getResultSet(), rowBounds);
    //2.shouldProcessMoreRows判斷是否需要映射後續的結果,實際還是翻頁處理,避免超過limit
    while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
      //3.進一步完善resultMap信息,主要是處理鑒別器的信息
      ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
      //4.讀取resultSet中的一行記錄併進行映射,轉化並返回目標對象
      Object rowValue = getRowValue(rsw, discriminatedResultMap);
      //5.保存映射結果對象
      storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
    }
  }

  private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap) throws SQLException {
    final ResultLoaderMap lazyLoader = new ResultLoaderMap();
    //4.1 根據resultMap的type屬性,實例化目標對象
    Object rowValue = createResultObject(rsw, resultMap, lazyLoader, null);
    if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
      //4.2 對目標對象進行封裝得到metaObjcect,為後續的賦值操作做好準備
      final MetaObject metaObject = configuration.newMetaObject(rowValue);
      boolean foundValues = this.useConstructorMappings;//取得是否使用構造函數初始化屬性值
      if (shouldApplyAutomaticMappings(resultMap, false)) {//是否使用自動映射
    	 //4.3一般情況下 autoMappingBehavior預設值為PARTIAL,對未明確指定映射規則的欄位進行自動映射
        foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, null) || foundValues;
      }
       //4.4 映射resultMap中明確指定需要映射的列
      foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, null) || foundValues;
      foundValues = lazyLoader.size() > 0 || foundValues;
      //4.5 如果沒有一個映射成功的屬性,則根據<returnInstanceForEmptyRow>的配置返回null或者結果對象
      rowValue = foundValues || configuration.isReturnInstanceForEmptyRow() ? rowValue : null;
    }
    return rowValue;
  }
  • 自動映射
  private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {
	//獲取resultSet中存在的,但是ResultMap中沒有明確映射的列,填充至autoMapping中
    List<UnMappedColumnAutoMapping> autoMapping = createAutomaticMappings(rsw, resultMap, metaObject, columnPrefix);
    boolean foundValues = false;
    if (!autoMapping.isEmpty()) {
      //遍歷autoMapping,通過自動匹配的方式為屬性複製
      for (UnMappedColumnAutoMapping mapping : autoMapping) {
    	//通過typeHandler從resultset中拿值
        final Object value = mapping.typeHandler.getResult(rsw.getResultSet(), mapping.column);
        if (value != null) {
          foundValues = true;
        }
        if (value != null || (configuration.isCallSettersOnNulls() && !mapping.primitive)) {
          // gcode issue #377, call setter on nulls (value is not 'found')
          //通過metaObject給屬性賦值
          metaObject.setValue(mapping.property, value);
        }
      }
    }
    return foundValues;
  }
  • 指定映射
  private boolean applyPropertyMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, ResultLoaderMap lazyLoader, String columnPrefix)
      throws SQLException {
	//從resultMap中獲取明確需要轉換的列名集合
    final List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
    boolean foundValues = false;
    //獲取ResultMapping集合
    final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
    for (ResultMapping propertyMapping : propertyMappings) {
      String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);//獲得列名,註意首碼的處理
      if (propertyMapping.getNestedResultMapId() != null) {
        // the user added a column attribute to a nested result map, ignore it
    	//如果屬性通過另外一個resultMap映射,則忽略
        column = null;
      }
      if (propertyMapping.isCompositeResult()//如果是嵌套查詢,column={prop1=col1,prop2=col2}
          || (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH)))//基本類型映射
          || propertyMapping.getResultSet() != null) {//嵌套查詢的結果
    	//獲得屬性值
        Object value = getPropertyMappingValue(rsw.getResultSet(), metaObject, propertyMapping, lazyLoader, columnPrefix);
        // issue #541 make property optional
        //獲得屬性名稱
        final String property = propertyMapping.getProperty();
        if (property == null) {//屬性名為空跳出迴圈
          continue;
        } else if (value == DEFERED) {//屬性名為DEFERED,延遲載入的處理
          foundValues = true;
          continue;
        }
        if (value != null) {
          foundValues = true;
        }
        if (value != null || (configuration.isCallSettersOnNulls() && !metaObject.getSetterType(property).isPrimitive())) {
          // gcode issue #377, call setter on nulls (value is not 'found')
          //通過metaObject為目標對象設置屬性值
          metaObject.setValue(property, value);
        }
      }
    }
    return foundValues;
  }

反射實例化對象的代碼比較長,但邏輯都比較清晰,上面的關鍵流程代碼也都加上了註釋,讀者可自行參照源碼閱讀。

總結

Mybatis核心原理就分析完了,相比較Spring源碼簡單了很多,但代碼的優雅度和優秀的設計思想一點也不亞於Spring,也是非常值得我們好好學習掌握的。不過這3篇只是分析了Mybaits的核心執行原理,另外還有插件怎麼擴展、攔截器會攔截哪些方法以及Mybatis和Spring的整合又是怎麼實現的呢?讀者們可以好好思考下,答案將在下一篇揭曉。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 負載均衡: 一聽這詞很多小伙伴嚇壞了,前人就喜歡搞一些看起來很高大上的詞,好讓後生望而敬畏.那我們一起來捋一捋. 負載就是負擔. 均衡就是平均分.這樣 一說就是負擔平均分. 伺服器也要減減壓 我們都知道伺服器是第三產業,服務行業,客戶來了,你不能不服務.客戶少還行,客戶多了一臺伺服器就頂不住了,怎麼 ...
  • 1 前言 經過《Maven一鍵部署Springboot到Docker倉庫,為自動化做準備》,Springboot的Docker鏡像已經準備好,也能在Docker上成功運行了,是時候放上Kubernetes跑一跑了。這非常簡單,一個yaml文件即可。 2 一鍵部署Springboot 2.1 準備ya ...
  • 一、複數和虛數類型 1.C語言有三種複數類型:float _Comples,double _Complex,long double _Complex float_complex類型的應包含兩個float類型的值,分別表示實部和虛部。 類似的C語言的三種虛數類型為1float _Imaginary,d ...
  • 1:IDEA安裝教程 開始安裝Idea,點擊next 點擊Browse選擇好安裝文件夾,點擊next 根據電腦選擇幾位,我的電腦是64位選擇64bit,Update PATH variable:是否將IDEA啟動目錄添加到環境變數中,即可以從cmd命令行中啟動IDEA,根據需要勾選 點擊Instal ...
  • shell之ping減少時間間隔&ping的次數 作為一位新手,檢測IP地址是否正常使用,ping是一個很不錯的選擇,可以更快的探測到當前網路的可用IP,併進行到文檔。 步驟如下: 首先:創建一個腳本文件併進行編輯: 1 # vim ping.sh 然後:寫入腳本,內容如下: #!/bin/bash ...
  • (1) 相關博文地址: SpringBoot + Vue + ElementUI 實現後臺管理系統模板 -- 前端篇(一):搭建基本環境:https://www.cnblogs.com/l-y-h/p/12930895.html SpringBoot + Vue + ElementUI 實現後臺管理 ...
  • 1、Django簡介 Django是Python語言中的一個web框架,Python語言中主流的web框架有Django、Tornado、Flask 等多種。Django相較與其它WEB框架,其優勢為: ​ 大而全,框架本身集成了ORM、模型綁定、模板引擎、緩存、Session等功能,是一個全能型框 ...
  • ## Java 集合框架 學習目標 會使用集合存儲數據 遍歷集合,取出數據 掌握每種集合的特性 學習方法 學習頂層!通過頂層介面/抽象類的共性方法,所有子類都可以使用 使用底層!頂層無法創建對象,需要使用具體的實現類創建對象 框架圖 第一章 Collction集合 一種工具,放在java.util ...
一周排行
    -Advertisement-
    Play Games
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...