1.概述
Executor接口是Mybatis的執行器,是Mybatis的調度中心,是SQL語句的生成和查詢緩存的維護。Executor是通過Configuration的newExecutor函數來生成的。
2.Executor結構
下面介紹一下Executor接口的實現類以及實現類的繼承類之間關係。
從上面的Executor的結構圖,我們得到了Executor接口有兩個實現類分別爲:CachingExecutor和BaseExecutor.
CachingExecutor類是一個裝飾類。
BaseExecutor類是一個模板類。
這裏針對不同的執行器(Executor)類型會創建不同的執行器對象。我們來看一看執行器類型枚舉類。
package org.apache.ibatis.session;
/**
*枚舉類型
*/
public enum ExecutorType {
SIMPLE, REUSE, BATCH
}
由上面的執行器類型枚舉類,我們知道了Mybatis共有三種執行器。分別的作用如下:
SimpleExecutor -- 最簡單的執行器,根據對應的sql直接執行即可,不會做一些額外的操作,拼接完SQL之後,直接交 給 StatementHandler 去執行。也是默認的執行器。
ReuseExecutor -- 可重用的執行器,重用的對象是Statement,也就是說該執行器會緩存同一個sql的Statement,省去 Statement的重新創建,優化性能。
BatchExecutor -- 通過批量操作來優化性能。通常需要注意的是批量更新操作,由於內部有緩存的實現,使用完成後記得調用 flushStatements
來清除緩存。
3.Executor接口的主要方法
package org.apache.ibatis.executor;
import java.sql.SQLException;
import java.util.List;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.transaction.Transaction;
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;
//創建緩存Key對象
CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql);
//判斷緩存中是否存在這個Key的結果
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();
}