MyBatis框架原理2:SqlSession執行過程
獲取SqlSession物件
SqlSession session = sqlSessionFactory.openSession();
首先通過SqlSessionFactory的openSession方法獲取SqlSession介面的實現類DefaultSqlSession物件。
public interface SqlSessionFactory { SqlSession openSession(); SqlSession openSession(boolean autoCommit); SqlSession openSession(Connection connection); SqlSession openSession(TransactionIsolationLevel level); SqlSession openSession(ExecutorType execType); SqlSession openSession(ExecutorType execType, boolean autoCommit); SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level); SqlSession openSession(ExecutorType execType, Connection connection); Configuration getConfiguration(); }
SqlSessionFactory介面提供一系列過載的openSession方法,其引數如下:
- boolean autoCommit:是否開啟JDBC事務的自動提交,預設為false。
- Connection:提供連線。
- TransactionIsolationLevel:定義事務隔離級別。
- ExecutorType:定義執行器型別。
DefaultSqlSessionFactory物件呼叫覆寫的openSession方法:
public SqlSession openSession() { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); }
得到一個定義了ExecutorType為configuration的預設執行器SIMPLE,事務隔離級別為null,JDBC事務自動提交為false的DefaultSqlSession物件。
獲取MapperProxy代理物件
有了DefaultSqlSession物件,以查詢一條資料為例,來看一下整個處理過程。
For example:
SqlSession session = sqlSessionFactory.openSession(); try { BlogMapper mapper = session.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(101); } finally { session.close(); }
MyBatis時序圖:
根據MyBatis文件推薦的方法,呼叫Mapper介面中的方法實現對資料庫的操作,上述例子中根據blog ID獲取Blog物件。
通過DefaultSqlSession物件的getMapper方法獲取的是一個MapperProxy代理物件,這也是Mapper介面不用實現類的原因。當呼叫BlogMapper中的方法時,由於BlogMapper是一個JDK動態代理物件,它會執行invoke方法,程式碼如下:
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { //判斷代理物件是否是一個類 if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); } else if (isDefaultMethod(method)) { return invokeDefaultMethod(proxy, method, args); } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } //生成MapperMethod物件 final MapperMethod mapperMethod = cachedMapperMethod(method); //執行execute方法 return mapperMethod.execute(sqlSession, args); } private MapperMethod cachedMapperMethod(Method method) { MapperMethod mapperMethod = methodCache.get(method); if (mapperMethod == null) { mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()); methodCache.put(method, mapperMethod); } return mapperMethod; } ...
invoke方法判斷代理的物件是否是一個類,由於代理物件是一個介面,所以通過cachedMapperMethod生成一個MappedMethod物件,然後執行execute方法,execute方法程式碼如下:
public Object execute(SqlSession sqlSession, Object[] args) { Object result; switch (command.getType()) { case INSERT: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.insert(command.getName(), param)); break; } case UPDATE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.update(command.getName(), param)); break; } case DELETE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.delete(command.getName(), param)); break; } case SELECT: if (method.returnsVoid() && method.hasResultHandler()) { executeWithResultHandler(sqlSession, args); result = null; } else if (method.returnsMany()) { result = executeForMany(sqlSession, args); } else if (method.returnsMap()) { result = executeForMap(sqlSession, args); } else if (method.returnsCursor()) { result = executeForCursor(sqlSession, args); } else { Object param = method.convertArgsToSqlCommandParam(args); result = sqlSession.selectOne(command.getName(), param); } 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; }
因為這裡是根據ID查詢一個物件,所以最終呼叫了DefaultSqlSession的selectOne方法,selectOne方法又呼叫自身selectList方法,最終將查詢操作委託給Executor:
@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; } } 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 { //根據id獲取MappedStatement物件 MappedStatement ms = configuration.getMappedStatement(statement); //wrapCollection方法處理集合引數 //委託Exector執行SQL 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(); } }
Executor執行過程
Executor(執行器),才是真正對JDBC操作的例項,它的結構如下:

CachingExecutor: SqlSession預設會呼叫CachingExecutor執行器的query方法,先從二級快取獲取資料,當無法從二級快取獲取資料時,則委託給BaseExcutor進行操作,CachingExecutor執行過程程式碼如下:
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, boundSql); @SuppressWarnings("unchecked") //從二級快取獲取資料 List<E> list = (List<E>) tcm.getObject(cache, key); //如果二級快取沒有資料則委託給BaseExcutor進行操作 if (list == null) { list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); tcm.putObject(cache, key, list); // issue #578 and #116 } return list; } } //如果沒有二級快取則委託給BaseExcutor進行操作 return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); }
BaseExecutor是一個抽象類,查詢操作時BaseExecutor首先從一級快取獲取資料,如果沒有則由其子類來進行資料庫操作,其query方法如下:
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; }
最後,我們例子中的查詢操作交給了SimpleExecutor這個子類,可以看到SimpleExecutor直接呼叫了JDBC的程式碼,最終得到了我們查詢的結果,其方法程式碼如下:
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { Statement stmt = null; try { Configuration configuration = ms.getConfiguration(); StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql); stmt = prepareStatement(handler, ms.getStatementLog()); return handler.<E>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()); handler.parameterize(stmt); return stmt; }