1. 程式人生 > >Mybatis中SqlSession下的四大核心元件分析

Mybatis中SqlSession下的四大核心元件分析

SqlSession下的四大核心元件
Mybatis中SqlSession下的四大核心元件:ParameterHandler 、ResultSetHandler 、StatementHandler 、Executor 。

關注原始碼類: Configuration.java

//ParameterHandler 處理sql的引數物件
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
    //包裝引數外掛
    parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
    return parameterHandler;
}

//ResultSetHandler 處理sql的返回結果集
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;
}

//StatementHandler 資料庫的處理物件
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);
    //包裝資料庫執行sql外掛
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
}

public Executor newExecutor(Transaction transaction) {
    //建立Mybatis的執行器:Executor
    return newExecutor(transaction, defaultExecutorType);
}

public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    //mybatis支援的三種執行器:batch、reuse、simple,其中預設支援的是simple
    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;
}

Mybatis的框架設計中,Mapper執行的過程中是通過Executor、ParameterHandler、StatementHandler、ResultHandler來完成資料庫操作並返回處理結果的。