作者:鄭志傑
mybatis 操作數據庫的過程
// 第一步:讀取mybatis-config.xml配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 第二步:構建SqlSessionFactory(框架初始化)
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().bulid();
// 第三步:打開sqlSession
SqlSession session = sqlSessionFactory.openSession();
// 第四步:獲取Mapper接口對象(底層是動態代理)
AccountMapper accountMapper = session.getMapper(AccountMapper.class);
// 第五步:調用Mapper接口對象的方法操作數據庫;
Account account = accountMapper.selectByPrimaryKey(1);
通過調用 session.getMapper (AccountMapper.class) 所得到的 AccountMapper 是一個動態代理對象,所以執行
accountMapper.selectByPrimaryKey (1) 方法前,都會被 invoke () 攔截,先執行 invoke () 中的邏輯。
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 要執行的方法所在的類如果是Object,直接調用,不做攔截處理
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
//如果是默認方法,也就是java8中的default方法
} else if (isDefaultMethod(method)) {
// 直接執行default方法
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
// 從緩存中獲取MapperMethod
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
從 methodCache 獲取對應 DAO 方法的 MapperMethod
MapperMethod 的主要功能是執行 SQL 語句的相關操作,在初始化的時候會實例化兩個對象:SqlCommand(Sql 命令)和 MethodSignature(方法簽名)。
/**
* 根據Mapper接口類型、接口方法、核心配置對象 構造MapperMethod對象
* @param mapperInterface
* @param method
* @param config
*/
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
// 將Mapper接口中的數據庫操作方法(如Account selectById(Integer id);)封裝成方法簽名MethodSignature
this.method = new MethodSignature(config, mapperInterface, method);
}
new SqlCommand()調用 SqlCommand 類構造方法:
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
// 獲取Mapper接口中要執行的某個方法的方法名
// 如accountMapper.selectByPrimaryKey(1)
final String methodName = method.getName();
// 獲取方法所在的類
final Class<?> declaringClass = method.getDeclaringClass();
// 解析得到Mapper語句對象(對配置文件中的<mapper></mapper>中的sql語句進行封裝)
MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
configuration);
if (ms == null) {
if (method.getAnnotation(Flush.class) != null) {
name = null;
type = SqlCommandType.FLUSH;
} else {
throw new BindingException("Invalid bound statement (not found): "
+ mapperInterface.getName() + "." + methodName);
}
} else {
// 如com.bjpowernode.mapper.AccountMapper.selectByPrimaryKey
name = ms.getId();
// SQL類型:增 刪 改 查
type = ms.getSqlCommandType();
if (type == SqlCommandType.UNKNOWN) {
throw new BindingException("Unknown execution method for: " + name);
}
}
}
private MapperMethod cachedMapperMethod(Method method) {
MapperMethod mapperMethod = (MapperMethod)this.methodCache.get(method);
if (mapperMethod == null) {
mapperMethod = new MapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration());
this.methodCache.put(method, mapperMethod);
}
return mapperMethod;
}
調用 mapperMethod.execute (sqlSession, args)
在 mapperMethod.execute () 方法中,我們可以看到:mybatis 定義了 5 種 SQL 操作類型:
insert/update/delete/select/flush。其中,select 操作類型又可以分為五類,這五類的返回結果都不同,分別對應:
・返回參數為空:executeWithResultHandler ();
・查詢多條記錄:executeForMany (),返回對象為 JavaBean
・返參對象為 map:executeForMap (), 通過該方法查詢數據庫,最終的返回結果不是 JavaBean,而是 Map
・遊標查詢:executeForCursor ();關於什麼是遊標查詢,自行百度哈;
・查詢單條記錄: sqlSession.selectOne (),通過該查詢方法,最終只會返回一條結果;
通過源碼追蹤我們可以不難發現:當調用 mapperMethod.execute () 執行 SQL 語句的時候,無論是
insert/update/delete/flush,還是 select(包括 5 種不同的 select), 本質上時通過 sqlSession 調用的。在 SELECT 操作中,雖然調用了 MapperMethod 中的方法,但本質上仍是通過 Sqlsession 下的 select (), selectList (), selectCursor (), selectMap () 等方法實現的。
而 SqlSession 的內部實現,最終是調用執行器 Executor(後面會細説)。這裏,我們可以先大概看一下 mybatis 在執行 SQL 語句的時候的調用過程:
以accountMapper.selectByPrimaryKey (1) 為例:
・調用 SqlSession.getMapper ():得到 xxxMapper (如 UserMapper) 的動態代理對象;
・調用
accountMapper.selectByPrimaryKey (1):在 xxxMapper 動態代理內部,會根據要執行的 SQL 語句類型 (insert/update/delete/select/flush) 來調用 SqlSession 對應的不同方法,如 sqlSession.insert ();
・在 sqlSession.insert () 方法的實現邏輯中,又會轉交給 executor.query () 進行查詢;
・executor.query () 又最終會轉交給 statement 類進行操作,到這裏就是 jdbc 操作了。
有人會好奇,為什麼要通過不斷的轉交,SqlSession->Executor->Statement,而不是直接調用 Statement 執行 SQL 語句呢?因為在調用 Statement 之前,會處理一些共性的邏輯,如在 Executor 的實現類 BaseExecutor 會有一級緩存相關的邏輯,在 CachingExecutor 中會有二級緩存的相關邏輯。如果直接調用 Statement 執行 SQL 語句,那麼在每個 Statement 的實現類中,都要寫一套一級緩存和二級緩存的邏輯,就顯得冗餘了。這一塊後面會細講。
// SQL命令(在解析mybatis-config.xml配置文件的時候生成的)
private final SqlCommand command;
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
// 從command對象中獲取要執行操作的SQL語句的類型,如INSERT/UPDATE/DELETE/SELECT
switch (command.getType()) {
// 插入
case INSERT: {
// 把接口方法裏的參數轉換成sql能識別的參數
// 如:accountMapper.selectByPrimaryKey(1)
// 把其中的參數"1"轉化為sql能夠識別的參數
Object param = method.convertArgsToSqlCommandParam(args);
// sqlSession.insert(): 調用SqlSession執行插入操作
// rowCountResult(): 獲取SQL語句的執行結果
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
// 更新
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
// sqlSession.insert(): 調用SqlSession執行更新操作
// rowCountResult(): 獲取SQL語句的執行結果
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
// 刪除
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
// sqlSession.insert(): 調用SqlSession執行更新操作
// rowCountResult(): 獲取SQL語句的執行結果
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
// 查詢
case SELECT:
// method.returnsVoid(): 返參是否為void
// method.hasResultHandler(): 是否有對應的結果處理器
if (method.returnsVoid() && method.hasResultHandler()) {
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 {
// 參數轉換 轉成sqlCommand參數
Object param = method.convertArgsToSqlCommandParam(args);
// 執行查詢 查詢單條數據
result = sqlSession.selectOne(command.getName(), param);
if (method.returnsOptional()
&& (result == null || !method.getReturnType().equals(result.getClass()))) {
result = Optional.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;
}
在上面,有多處出現這樣一行代碼:
method.convertArgsToSqlCommandParam (args),該方法的作用就是將方法參數轉換為 SqlCommandParam;具體交由
paramNameResolver.getNamedParams () 實現。在看 paramNameResolver.getNamedParams () 之前,我們先來看下 paramNameResolver 是什麼東西?
public Object convertArgsToSqlCommandParam(Object[] args) {
return paramNameResolver.getNamedParams(args);
}
在前面,我們在實例化 MethodSignature 對象 (new MethodSignature) 的時候,在其構造方法中,會實例化 ParamNameResolver 對象,該對象主要用來處理接口形式的參數,最後會把參數處放在一個 map(即屬性 names)中。map 的 key 為參數的位置,value 為參數的名字。
public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) {
...
this.paramNameResolver = new ParamNameResolver(configuration, method);
}
對 names 字段的解釋:
假設在 xxxMapper 中有這麼一個接口方法 selectByIdAndName ()
・selectByIdAndName (@Param ("id") String id, @Param ("name") String name) 轉化為 map 為 {{0, "id"}, {1, "name"}}
・selectByIdAndName (String id, String name) 轉化為 map 為 {{0, "0"}, {1, "1"}}
・selectByIdAndName (int a, RowBounds rb, int b) 轉化為 map 為 {{0, "0"}, {2, "1"}}
構造方法的會經歷如下的步驟
- 通過反射得到方法的參數類型和方法的參數註解註解,
method.getParameterAnnotations () 方法返回的是註解的二維數組,每一個方法的參數包含一個註解數組。 - 遍歷所有的參數
- 首先判斷這個參數的類型是否是特殊類型,RowBounds 和 ResultHandler,是的話跳過,咱不處理
- 判斷這個參數是否是用來 Param 註解,如果使用的話 name 就是 Param 註解的值,並把 name 放到 map 中,鍵為參數在方法中的位置,value 為 Param 的值
- 如果沒有使用 Param 註解,判斷是否開啓了 UseActualParamName,如果開啓了,則使用 java8 的反射得到方法的名字,此處容易造成異常,
具體原因參考上一篇博文.
- 如果以上條件都不滿足的話,則這個參數的名字為參數的下標
// 通用key前綴,因為key有param1,param2,param3等;
public static final String GENERIC_NAME_PREFIX = "param";
// 存放參數的位置和對應的參數名
private final SortedMap<Integer, String> names;
// 是否使用@Param註解
private boolean hasParamAnnotation;
public ParamNameResolver(Configuration config, Method method) {
// 通過註解得到方法的參數類型數組
final Class<?>[] paramTypes = method.getParameterTypes();
// 通過反射得到方法的參數註解數組
final Annotation[][] paramAnnotations = method.getParameterAnnotations();
// 用於存儲所有參數名的SortedMap對象
final SortedMap<Integer, String> map = new TreeMap<>();
// 參數註解數組長度,即方法入參中有幾個地方使用了@Param
// 如selectByIdAndName(@Param("id") String id, @Param("name") String name)中,paramCount=2
int paramCount = paramAnnotations.length;
// 遍歷所有的參數
for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
// 判斷這個參數的類型是否是特殊類型,RowBounds和ResultHandler,是的話跳過
if (isSpecialParameter(paramTypes[paramIndex])) {
continue;
}
String name = null;
for (Annotation annotation : paramAnnotations[paramIndex]) {
// 判斷這個參數是否使用了@Param註解
if (annotation instanceof Param) {
// 標記當前方法使用了Param註解
hasParamAnnotation = true;
// 如果使用的話name就是Param註解的值
name = ((Param) annotation).value();
break;
}
}
// 如果經過上面處理,參數名還是null,則説明當前參數沒有指定@Param註解
if (name == null) {
// 判斷是否開啓了UseActualParamName
if (config.isUseActualParamName()) {
// 如果開啓了,則使用java8的反射得到該參數對應的屬性名
name = getActualParamName(method, paramIndex);
}
// 如果name還是為null
if (name == null) {
// use the parameter index as the name ("0", "1", ...)
// 使用參數在map中的下標作為參數的name,如 ("0", "1", ...)
name = String.valueOf(map.size());
}
}
// 把參數放入到map中,key為參數在方法中的位置,value為參數的name(@Param的value值/參數對應的屬性名/參數在map中的位置下標)
map.put(paramIndex, name);
}
// 最後使用Collections工具類的靜態方法將結果map變為一個不可修改類型
names = Collections.unmodifiableSortedMap(map);
}
getNamedParams(): 該方法會將參數名和參數值對應起來,並且還會額外保存一份以 param 開頭加參數順序數字的值
public Object getNamedParams(Object[] args) {
// 這裏的names就是ParamNameResolver中的names,在構造ParamNameResolver對象的時候,創建了該Map
// 獲取方法參數個數
final int paramCount = names.size();
// 沒有參數
if (args == null || paramCount == 0) {
return null;
// 只有一個參數,並且沒有使用@Param註解。
} else if (!hasParamAnnotation && paramCount == 1) {
// 直接返回,不做任務處理
return args[names.firstKey()];
} else {
// 包裝成ParamMap對象。這個對象繼承了HashMap,重寫了get方法。
final Map<String, Object> param = new ParamMap<>();
int i = 0;
// 遍歷names中的所有鍵值對
for (Map.Entry<Integer, String> entry : names.entrySet()) {
// 將參數名作為key, 對應的參數值作為value,放入結果param對象中
param.put(entry.getValue(), args[entry.getKey()]);
// 用於添加通用的參數名稱,按順序命名(param1, param2, ...)
final String genericParamName = GENERIC_NAME_PREFIX + (i + 1);
// 確保不覆蓋以@Param 命名的參數
if (!names.containsValue(genericParamName)) {
param.put(genericParamName, args[entry.getKey()]);
}
i++;
}
return param;
}
}
}
getNamedParams () 總結:
- 當只有一個參數的時候,直接返回,不做任務處理;
- 否則,存入 Map 中,鍵值對形式為:paramName=paramValue
・selectByIdAndName (@Param ("id") String id, @Param ("name") String name): 傳入的參數是 ["1", "張三"],最後解析出來的 map 為:{“id”:”1”,”“name”:” 張三”}
・selectByIdAndName (String id, @Param ("name") String name): 傳入的參數是 ["1", "張三"],最後解析出來的 map 為:{“param1”:”1”,”“name”:” 張三”}
假設執行的 SQL 語句是 select 類型,繼續往下看代碼
在 mapperMethod.execute (), 當
convertArgsToSqlCommandParam () 方法處理完方法參數後,假設我們此時調用的是查詢單條記錄,那麼接下來會執行 sqlSession.selectOne () 方法。
sqlSession.selectOne () 源碼分析:
sqlSession.selectOne () 也是調的 sqlSession.selectList () 方法,只不過只返回 list 中的第一條數據。當 list 中有多條數據時,拋異常。
@Override
public <T> T selectOne(String statement, Object parameter) {
// 調用當前類的selectList方法
List<T> list = this.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;
}
}
sqlSession.selectList () 方法
@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 {
// 從Configuration裏的mappedStatements里根據key(id的全路徑)獲取MappedStatement對象
MappedStatement ms = configuration.getMappedStatement(statement);
// 調用Executor的實現類BaseExecutor的query()方法
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();
}
}
在 sqlSession.selectList () 方法中,我們可以看到調用了 executor.query (),假設我們開啓了二級緩存,那麼 executor.query () 調用的是 executor 的實現類 CachingExecutor 中的 query (),二級緩存的邏輯就是在 CachingExecutor 這個類中實現的。
關於 mybatis 二級緩存:
二級緩存默認是不開啓的,需要手動開啓二級緩存,實現二級緩存的時候,MyBatis 要求返回的 POJO 必須是可序列化的。緩存中存儲的是序列化之後的,所以不同的會話操作對象不會改變緩存。
怎麼開啓二級緩存:
<settings>
<setting name = "cacheEnabled" value = "true" />
</settings>
怎麼使用二級緩存?
- 首先肯定是要開啓二級緩存啦~
- 除此之外,要使用二級緩存還要滿足以下條件:
・當會話提交之後才會填充二級緩存(為什麼?後面會解釋)
・SQL 語句相同,參數相同
・相同的 statementID
・RowBounds 相同
為什麼要會話提交後才會填充二級緩存?
首先,我們知道,與一級緩存(會話級緩存)不同的是,二級緩存是跨線程使用的,也就是多個會話可以一起使用同一個二級緩存。假設現在不用提交便可以填充二級緩存,我們看看會存在什麼問題?
假設會話二現在對數據庫進行了修改操作,修改完進行了查詢操縱,如果不用提交就會填充二級緩存的話,這時候查詢操作會把剛才修改的數據填充到二級緩存中,如果此時剛好會話一執行了查詢操作,便會查詢到二級緩存中的數據。如果會話二最終回滾了剛才的修改操作,那麼會話一就相當於發生了髒讀。
實際上,查詢的時候會填充緩存,只不過此時是填充在暫存區,而不是填充在真正的二級緩存區中。而上面所説的要會話提交後才會填充二級緩存,指的是將暫存區中的緩存刷到真正的二級緩存中。啊???那不對呀,填充在暫存區,那此時會話一來查詢,豈不是還會從暫存區中取到緩存,從而導致髒讀?別急,接着往下看。
對於查詢操作,每次取緩存都是從真正的二級緩存中取緩存,而不是從暫存區中取緩存。
好了,我們接着看源碼~
CachingExecutor.query () 源碼:
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
// 獲取要執行的sql語句 sql語句在解析xml的時候就已經解析好了
BoundSql boundSql = ms.getBoundSql(parameterObject);
// 生成二級緩存key
CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
// 調用重載方法
return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
調用重載方法:query ()
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
// 獲取mybatis的二級緩存配置<cache>
Cache cache = ms.getCache();
// 如果配置了二級緩存
if (cache != null) {
// 是否要刷新緩存,是否手動設置了需要清空緩存
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, boundSql);
@SuppressWarnings("unchecked")
// 從二級緩存中獲取值
List<E> list = (List<E>) tcm.getObject(cache, key);
// 從二級緩存中取不到值
if (list == null) {
// 交由delegate查詢 這裏的delegate指向的是BaseExecutor
// BaseExecutor中實現了一級緩存的相關邏輯
// 也就是説,當在二級緩存中獲取不到值的時候,會從一級緩存中獲取,一級緩存要是還是獲取不到
// 才會去查詢數據庫
list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
// 將查詢結果存放在暫存區中,只有會話提交後才會將數據刷到二級緩存,避免髒讀問題
tcm.putObject(cache, key, list); // issue #578 and #116
}
return list;
}
}
return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
接着,我們看下 BaseExecutor.query () 是怎麼實現一級緩存邏輯的:
@SuppressWarnings("unchecked")
@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;
}
當從一級緩存中獲取不到數據時,會查數據庫:
調用
BaseExecutor.queryFromDatabase()
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 {
// 執行查詢操作
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;
}
調用 BaseExecutor.doQuery ():在 BaseExecutor 中,doQuery () 只是個抽象方法,具體交由子類實現:
protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
throws SQLException;
從前面的流程中可知,在每次執行 CURD 的時候,都需要獲取 SqlSession 這個對象,接口如下:
可以看出來這個接口主要定義類關於 CRUD、數據庫事務、數據庫刷新等相關操作。下面看它的默認實現類:
可以看到 DefaultSqlSession 實現了 SqlSession 中的方法,(其實我們自己也可根據需要去實現)。而在 DefaultSqlSession 類中有一個很重要的屬性,就是 Mybatis 的執行器(Executor)。
Executor 介紹:
Executor 執行器,是 mybatis 中執行查詢的主要代碼,Executor 分為三種:
・簡單執行器 SimpleExecutor
・可重用執行器 ReuseExecutor
・批量執行器 BatchExecutor
默認使用的執行器是 SimpleExecutor,可以在 mybatis 的配置文件中設置使用哪種執行器
public class Configuration {
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
}
Executor 類圖:
假設我們使用的就是默認的執行器,SimpleExecutor。我們來看下 SimpleExecutor.doQuery ()
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
// 這裏就進入jdbc了
Statement stmt = null;
try {
// 獲取核心配置對象
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
//預編譯SQL語句
stmt = prepareStatement(handler, ms.getStatementLog());
// 執行查詢
return handler.query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
// 獲取連接 這裏的連接是代理連接
Connection connection = getConnection(statementLog);
// 預編譯
stmt = handler.prepare(connection, transaction.getTimeout());
// 給預編譯sql語句設置參數
handler.parameterize(stmt);
return stmt;
}
在上面的源碼中,我們可以看到 StatementHandler,它是用來幹嘛的?
在 mybatis 中,通過 StatementHandler 來處理與 JDBC 的交互,我們看下 StatementHandler 的類圖:
可以看出,跟 Executor 的繼承實現很像,都有一個 Base,Base 下面又有幾個具體實現子類,很明顯,採用了模板模式。不同於 CacheExecutor 用於二級緩存之類的實際作用,這裏的 RoutingStatementHandler 僅用於維護三個 Base 子類的創建與調用。
•BaseStatementHandler
・SimpleStatementHandler:JDBC 中的 Statement 接口,處理簡單 SQL 的
・CallableStatementHandler:JDBC 中的 PreparedStatement,預編譯 SQL 的接口
・PreparedStatementHandler:JDBC 中的 CallableStatement,用於執行存儲過程相關的接口
・RoutingStatementHandler:路由三個 Base 子類,負責其創建及調用
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
switch (ms.getStatementType()) {
// 策略模式:根據不同語句類型 選用不同的策略實現類
case STATEMENT:
delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
case PREPARED:
delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
case CALLABLE:
delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
default:
throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
}
}
嗯,很眼熟的策略模式,按照 statementType 的值來決定返回哪種 StatementHandler。
那這裏的 statementType 是在哪裏賦值的呢?我們看下 MappedStatement 的構造方法:
public Builder(Configuration configuration, String id, SqlSource sqlSource, SqlCommandType sqlCommandType) {
...
// 構造方法中默認取值為PREPARED
mappedStatement.statementType = StatementType.PREPARED;
...
}
如果不想使用的 StatementType.PREPARED,怎麼自定義呢?
(1) 在 xxxMapper.xml 中:可以通過 <select /> 的 statementType 屬性指定
<select id="getAll" resultType="Student2" statementType="CALLABLE">
SELECT * FROM Student
</select>
(2) 如果採用的是註解開發:通過 @SelectKey 的 statementType 屬性指定
@SelectKey(keyProperty = "account",
before = false,
statementType = StatementType.STATEMENT,
statement = "select * from account where id = #{id}",
resultType = Account.class)
Account selectByPrimaryKey(@Param("id") Integer id);
到此,select 類型的 SQL 語句就基本執行完畢了,我們來總結一下 mybatis
MyBatis 的主要的核心部件有以下幾個:
SqlSession: 作為 MyBatis 工作的主要頂層 API,表示和數據庫交互的會話,完成必要數據庫增刪改查功能;
Executor: MyBatis 執行器,是 MyBatis 調度的核心,負責 SQL 語句的生成和查詢緩存的維護;
StatementHandler: 封裝了 JDBC Statement 操作,負責對 JDBC statement 的操作,如設置參數、將 Statement 結果集轉換成 List 集合。
ParameterHandler: 負責對用户傳遞的參數轉換成 JDBC Statement 所需要的參數;
ResultSetHandler: 負責將 JDBC 返回的 ResultSet 結果集對象轉換成 List 類型的集合;
TypeHandler: 負責 java 數據類型和 jdbc 數據類型之間的映射和轉換;
MappedStatement: MappedStatement 維護了一條 <select|update|delete|insert> 節點的封裝;
SqlSource: 負責根據用户傳遞的 parameterObject,動態地生成 SQL 語句,將信息封裝到 BoundSql 對象中,並返回;
BoundSql: 表示動態生成的 SQL 語句以及相應的參數信息;
Configuration: MyBatis 所有的配置信息都維持在 Configuration 對象之中;