MyBatis SQL執行

LZC發表於2020-07-27

SQL 語句的執行涉及多個元件 ,其中比較重要的是 ExecutorStatementHandlerParameterHandlerResultSetHandler

  • Executor 主要負責維護一級快取和二級快取,並提供事務管理的相關操作,它會將資料庫相關操作委託給StatementHandler完成。
  • StatementHandler 首先通過 ParameterHandler 完成 SQL 語句的實參繫結,然後通過 java.sql.Statement 物件執行 SQL 語句並得到結果集,最後通過 ResultSetHandler 完成結果集的對映,得到結果物件並返回。

SqlSession物件表示MyBaits框架與資料庫建立的會話,我們可以通過SqlSession例項完成對資料庫的增刪改查操作。SqlSession是一個介面,它的預設實現為DefaultSqlSession

下面以selectOne為例

// DefaultSqlSession.java
public class DefaultSqlSession implements SqlSession {
    private final Configuration configuration;
    private final Executor executor;
    private final boolean autoCommit;
    private boolean dirty;
    private List<Cursor<?>> cursorList;

    @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.<T>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;
        }
    }

    @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 {
            // 根據 statement 獲取對應的 MappedStatement
            // statement = Mapper類路徑.方法名
            // 如com.example.demo.UserMapper.getUserByUserName
            MappedStatement ms = configuration.getMappedStatement(statement);
            // 這裡的 executor 使用的是 CachingExecutor
            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();
        }
    }
}
// CachingExecutor.java
public class CachingExecutor implements Executor {
    @Override
    public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
        BoundSql boundSql = ms.getBoundSql(parameterObject);
        // 建立 CacheKey 物件
        CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
        // 查詢
        return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
    }

    @Override
    public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
        throws SQLException {
        Cache cache = ms.getCache();
        if (cache != null) {
            // 這裡判斷是否需要清空快取
            flushCacheIfRequired(ms);
            if (ms.isUseCache() && resultHandler == null) {
                // 這裡是儲存過程相關的
                ensureNoOutParams(ms, parameterObject, boundSql);
                // 從二級快取中獲取結果
                @SuppressWarnings("unchecked")
                List<E> list = (List<E>) tcm.getObject(cache, key);
                if (list == null) {
                    // 如果不存在,則從資料庫中查詢
                    // 這裡的 delegate 為 SimpleExecutor,SimpleExecutor繼承了BaseExecutor
                    // 這裡的 query 方法是 BaseExecutor 類中的 
                    list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
                    // 快取結果到二級快取中
                    tcm.putObject(cache, key, list); // issue #578 and #116
                }
                return list;
            }
        }
        // 不使用快取,則從資料庫中查詢
        // 這裡的 delegate 為 SimpleExecutor,SimpleExecutor繼承了BaseExecutor
        // 這裡的 query 方法是 BaseExecutor 類中的 
        return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
    }
}
// BaseExecutor.java
public abstract class BaseExecutor implements Executor {
    @Override
    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 {
            // 執行讀操作
            // 這裡的 doQuery 由子類SimpleExecutor實現
            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.java
public class SimpleExecutor extends BaseExecutor {
    @Override
    public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        Statement stmt = null;
        try {
            // 獲取 Configuration
            Configuration configuration = ms.getConfiguration();
            // 建立 StatementHandler 物件
            StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
            // 獲取 Statement 物件
            stmt = prepareStatement(handler, ms.getStatementLog());
            // 執行查詢操作
            // 這裡的 handler 為 RoutingStatementHandler
            return handler.<E>query(stmt, resultHandler);
        } finally {
            // 關閉 StatementHandler 物件
            closeStatement(stmt);
        }
    }

    private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
        Statement stmt;
        // 獲得 Connection 物件
        Connection connection = getConnection(statementLog);
        // 建立 Statement 或 PrepareStatement 物件
        stmt = handler.prepare(connection, transaction.getTimeout());
        // 設定 SQL 上的引數,例如 PrepareStatement 物件上的佔位符設定上使用者傳遞過來的值
        // 這裡的 handler 為 RoutingStatementHandler
        handler.parameterize(stmt);
        return stmt;
    }
}
// RoutingStatementHandler.java
public class RoutingStatementHandler implements StatementHandler {

    // 完成SQL語句的實參繫結
    @Override
    public void parameterize(Statement statement) throws SQLException {
        // 這裡的 delegate 為 PreparedStatementHandler
        delegate.parameterize(statement);
    }

    @Override
    public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
        // 這裡的 delegate 為 PreparedStatementHandler
        return delegate.<E>query(statement, resultHandler);
    }
}
// PreparedStatementHandler.java
public class PreparedStatementHandler extends BaseStatementHandler {
    // 完成SQL語句的實參繫結
    @Override
    public void parameterize(Statement statement) throws SQLException {
        // 這裡的 parameterHandler 為
        parameterHandler.setParameters((PreparedStatement) statement);
    }

    @Override
    public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
        PreparedStatement ps = (PreparedStatement) statement;
        ps.execute();
        // 這裡的 resultSetHandler 為 DefaultResultSetHandler
        // handleResultSets方法的功能是將查詢結果封裝成使用者設定的返回型別
        return resultSetHandler.<E> handleResultSets(ps);
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章