概述java
Executor(org.apache.ibatis.executor.Executor),執行器。sql
public interface Executor { ResultHandler NO_RESULT_HANDLER = null; int update(MappedStatement ms, Object parameter) throws SQLException; <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey cacheKey, BoundSql boundSql) throws SQLException; <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException; List<BatchResult> flushStatements() throws SQLException; void commit(boolean required) throws SQLException; void rollback(boolean required) throws SQLException; CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql); boolean isCached(MappedStatement ms, CacheKey key); void clearLocalCache(); void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key, Class<?> targetType); Transaction getTransaction(); void close(boolean forceRollback); boolean isClosed(); void setExecutorWrapper(Executor executor); }
它主要負責執行給定的MappedStatement對象和參數對象,以獲取最終的結果List。在執行過程當中,還涉及到緩存的操做和維護。apache
Executor對象隨着SqlSession的建立而建立,被保存在SqlSession對象中,所以Executor的生命週期與SqlSession一致。
緩存
// DefaultSqlSessionFactory建立DefaultSqlSession的邏輯 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); // 建立執行器 final Executor executor = configuration.newExecutor(tx, execType); // 建立SqlSession 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(); } }
mybatis框架內部的執行器體系以下:session
BaseExecutor是全部執行器實現類的基類,它只實現了基本的功能,其中包括對本地緩存(也就是咱們所說的一級緩存)的操做和維護。子類須要實現具體的執行邏輯,包括:doUpdate更新邏輯、doQuery查詢邏輯以及doFlushStatements批處理邏輯。mybatis
SimpleExecutor是Executor的最簡單實現,它不支持批處理,且執行邏輯很簡單:app
建立StatemenHandler對象框架
調用StatemenHandler生成要執行的Statement(jdbc接口)對象fetch
調用StatemenHandler執行Statement對象,並處理產生的結果,而後返回ui
ReuseExecutor額外在內部維護了一個Map,它能夠實現複用尚未關閉鏈接的Statement對象。
// key爲sql語句,value爲Statement對象 private final Map<String, Statement> statementMap = new HashMap<String, Statement>();
BatchExecutor的doUpdate更新操做是批量執行,每一次更新操做保存在內部的statementList中,每調用一次flushStatements()進行一次批量執行。commit時會調用flushStatements(),查詢操做時也會調用flushStatements()。
CachingExecutor,緩存執行器。能夠把它理解爲一個裝飾器,主要負責二級緩存的操做和維護。