前言
上一篇文章提到了MyBatis是如何構建配置類的,也說了MyBatis在運行過程中主要分為兩個階段,第一是構建,第二就是執行,所以這篇文章會帶大家來了解一下MyBatis是如何從構建完畢,到執行我們的第一條SQL語句的。之后這部分內容會歸置到公眾號菜單欄:連載中…-框架分析中,歡迎探討!
入口(代理對象的生成)
public static void main(String[] args) throws Exception { /******************************構造******************************/ String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); //創建SqlSessionFacory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); /******************************分割線******************************/ /******************************執行******************************/ //SqlSession是幫我們操作數據庫的對象 SqlSession sqlSession = sqlSessionFactory.openSession(); //獲取Mapper DemoMapper mapper = sqlSession.getMapper(DemoMapper.class); Map<String,Object> map = new HashMap<>(); map.put("id","123"); System.out.println(mapper.selectAll(map)); sqlSession.close(); sqlSession.commit(); }
首先在沒看源碼之前希望大家可以回憶起來,我們在使用原生MyBatis的時候(不與Spring進行整合),操作SQL的只需要一個對象,那就是SqlSession對象,這個對象就是專門與數據庫進行交互的。
我們在構造篇有提到,Configuration對象是在SqlSessionFactoryBuilder中的build方法中調用了XMLConfigBuilder的parse方法進行解析的,但是我們沒有提到這個Configuration最終的去向。講這個之前我們可以思考一下,這個Configuration生成之后,會在哪個環節被使用?毋庸置疑,它作為一個配置文件的整合,里面包含了數據庫連接相關的信息,SQL語句相關信息等,在查詢的整個流程中必不可少,而剛才我們又說過,SqlSession實際上是我們操作數據庫的一個真實對象,所以可以得出這個結論:Configuration必然和SqlSession有所聯系。
源碼:
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) { try { //解析config.xml(mybatis解析xml是用的 java dom) dom4j sax... XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties); //parse(): 解析config.xml里面的節點 return build(parser.parse()); } catch (Exception e) { throw ExceptionFactory.wrapException("Error building SqlSession.", e); } finally { ErrorContext.instance().reset(); try { inputStream.close(); } catch (IOException e) { // Intentionally ignore. Prefer previous error. } } } public SqlSessionFactory build(Configuration config) { //注入到SqlSessionFactory return new DefaultSqlSessionFactory(config); } public DefaultSqlSessionFactory(Configuration configuration) { this.configuration = configuration; }
實際上我們從源碼中可以看到,Configuration是SqlSessionFactory的一個屬性,而SqlSessionFactoryBuilder在build方法中實際上就是調用XMLConfigBuilder對xml文件進行解析,然后注入到SqlSessionFactory中。
明確了這一點我們就接着往下看。
根據主線我們現在得到了一個SqlSessionFactory對象,下一步就是要去獲取SqlSession對象,這里會調用SqlSessionFactory.openSession()方法來獲取,而openSession中實際上就是對SqlSession做了進一步的加工封裝,包括增加了事務、執行器等。
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { Transaction tx = null; try { //對SqlSession對象進行進一步加工封裝 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(); } }
到這里可以得出的小結論是,SqlSessionFactory對象中由於存在Configuration對象,所以它保存了全局配置信息,以及初始化環境和DataSource,而DataSource的作用就是用來開辟鏈接,當我們調用openSession方法時,就會開辟一個連接對象並傳給SqlSession對象,交給SqlSession來對數據庫做相關操作。
接着往下,現在我們獲取到了一個SqlSession對象,而執行過程就是從這里開始的。
我們可以開始回憶了,平時我們使用MyBatis的時候,我們寫的DAO層應該長這樣:
public interface DemoMapper { public List<Map<String,Object>> selectAll(Map<String,Object> map); }
實際上它是一個接口,而且並沒有實現類,而我們卻可以直接對它進行調用,如下:
DemoMapper mapper = sqlSession.getMapper(DemoMapper.class); Map<String,Object> map = new HashMap(); map.put("id","123"); System.out.println(mapper.selectAll(map));
可以猜測了,MyBatis底層一定使用了動態代理,來對這個接口進行代理,我們實際上調用的是MyBatis為我們生成的代理對象。
我們在獲取Mapper的時候,需要調用SqlSession的getMapper()方法,那么就從這里深入。
//getMapper方法最終會調用到這里,這個是MapperRegistry的getMapper方法 @SuppressWarnings("unchecked") public <T> T getMapper(Class<T> type, SqlSession sqlSession) { //MapperProxyFactory 在解析的時候會生成一個map map中會有我們的DemoMapper的Class final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }
可以看到這里mapperProxyFactory對象會從一個叫做knownMappers的對象中以type為key取出值,這個knownMappers是一個HashMap,存放了我們的DemoMapper對象,而這里的type,就是我們上面寫的Mapper接口。那么就有人會問了,這個knownMappers是在什么時候生成的呢?實際上這是我上一篇漏講的一個地方,在解析的時候,會調用parse()方法,相信大家都還記得,這個方法內部有一個bindMapperForNamespace方法,而就是這個方法幫我們完成了knownMappers的生成,並且將我們的Mapper接口put進去。
public void parse() { //判斷文件是否之前解析過 if (!configuration.isResourceLoaded(resource)) { //解析mapper文件 configurationElement(parser.evalNode("/mapper")); configuration.addLoadedResource(resource); //這里:綁定Namespace里面的Class對象* bindMapperForNamespace(); } //重新解析之前解析不了的節點 parsePendingResultMaps(); parsePendingCacheRefs(); parsePendingStatements(); } private void bindMapperForNamespace() { String namespace = builderAssistant.getCurrentNamespace(); if (namespace != null) { Class<?> boundType = null; try { boundType = Resources.classForName(namespace); } catch (ClassNotFoundException e) { } if (boundType != null) { if (!configuration.hasMapper(boundType)) { configuration.addLoadedResource("namespace:" + namespace); //這里將接口class傳入 configuration.addMapper(boundType); } } } } public <T> void addMapper(Class<T> type) { if (type.isInterface()) { if (hasMapper(type)) { throw new BindingException("Type " + type + " is already known to the MapperRegistry."); } boolean loadCompleted = false; try { //這里將接口信息put進konwMappers。 knownMappers.put(type, new MapperProxyFactory<>(type)); MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); parser.parse(); loadCompleted = true; } finally { if (!loadCompleted) { knownMappers.remove(type); } } } }
所以我們在getMapper之后,獲取到的是一個Class,之后的代碼就簡單了,就是生成標准的代理類了,調用newInstance()方法。
public T newInstance(SqlSession sqlSession) { //首先會調用這個newInstance方法 //動態代理邏輯在MapperProxy里面 final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache); //通過這里調用下面的newInstance方法 return newInstance(mapperProxy); } @SuppressWarnings("unchecked") protected T newInstance(MapperProxy<T> mapperProxy) { //jdk自帶的動態代理 return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy); }
到這里,就完成了代理對象(MapperProxy)的創建,很明顯的,MyBatis的底層就是對我們的接口進行代理類的實例化,從而操作數據庫。
但是,我們好像就得到了一個空盪盪的對象,調用方法的邏輯呢?好像根本就沒有看到,所以這也是比較考驗Java功底的地方。
我們知道,一個類如果要稱為代理對象,那么一定需要實現InvocationHandler接口,並且實現其中的invoke方法,進行一波推測,邏輯一定在invoke方法中。
於是就可以點進MapperProxy類,發現其的確實現了InvocationHandler接口,這里我將一些用不到的代碼先刪除了,只留下有用的代碼,便於分析
/** * @author Clinton Begin * @author Eduardo Macarron */ public class MapperProxy<T> implements InvocationHandler, Serializable { public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) { //構造 this.sqlSession = sqlSession; this.mapperInterface = mapperInterface; this.methodCache = methodCache; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //這就是一個很標准的JDK動態代理了 //執行的時候會調用invoke方法 try { if (Object.class.equals(method.getDeclaringClass())) { //判斷方法所屬的類 //是不是調用的Object默認的方法 //如果是 則不代理,不改變原先方法的行為 return method.invoke(this, args); } else if (method.isDefault()) { //對於默認方法的處理 //判斷是否為default方法,即接口中定義的默認方法。 //如果是接口中的默認方法則把方法綁定到代理對象中然后調用。 //這里不詳細說 if (privateLookupInMethod == null) { return invokeDefaultMethodJava8(proxy, method, args); } else { return invokeDefaultMethodJava9(proxy, method, args); } } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } //如果不是默認方法,則真正開始執行MyBatis代理邏輯。 //獲取MapperMethod代理對象 final MapperMethod mapperMethod = cachedMapperMethod(method); //執行 return mapperMethod.execute(sqlSession, args); } private MapperMethod cachedMapperMethod(Method method) { //動態代理會有緩存,computeIfAbsent 如果緩存中有則直接從緩存中拿 //如果緩存中沒有,則new一個然后放入緩存中 //因為動態代理是很耗資源的 return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration())); } }
在方法開始代理之前,首先會先判斷是否調用了Object類的方法,如果是,那么MyBatis不會去改變其行為,直接返回,如果是默認方法,則綁定到代理對象中然后調用(不是本文的重點),如果都不是,那么就是我們定義的mapper接口方法了,那么就開始執行。
執行方法需要一個MapperMethod對象,這個對象是MyBatis執行方法邏輯使用的,MyBatis這里獲取MapperMethod對象的方式是,首先去方法緩存中看看是否已經存在了,如果不存在則new一個然后存入緩存中,因為創建代理對象是十分消耗資源的操作。總而言之,這里會得到一個MapperMethod對象,然后通過MapperMethod的excute()方法,來真正地執行邏輯。
執行邏輯
語句類型判斷
這里首先會判斷SQL的類型:SELECT|DELETE|UPDATE|INSERT,我們這里舉的例子是SELECT,其它的其實都差不多,感興趣的同學可以自己去看看。判斷SQL類型為SELECT之后,就開始判斷返回值類型,根據不同的情況做不同的操作。然后開始獲取參數--》執行SQL。
//execute() 這里是真正執行SQL的地方 public Object execute(SqlSession sqlSession, Object[] args) { //判斷是哪一種SQL語句 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()) { //返回Map result = executeForMap(sqlSession, args); } else if (method.returnsCursor()) { //返回Cursor result = executeForCursor(sqlSession, args); } else { 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; } //返回值多行 這里調用這個方法 private <E> Object executeForMany(SqlSession sqlSession, Object[] args) { //返回值多行時執行的方法 List<E> result; //param是我們傳入的參數,如果傳入的是Map,那么這個實際上就是Map對象 Object param = method.convertArgsToSqlCommandParam(args); if (method.hasRowBounds()) { //如果有分頁 RowBounds rowBounds = method.extractRowBounds(args); //執行SQL的位置 result = sqlSession.selectList(command.getName(), param, rowBounds); } else { //如果沒有 //執行SQL的位置 result = sqlSession.selectList(command.getName(), param); } // issue #510 Collections & arrays support if (!method.getReturnType().isAssignableFrom(result.getClass())) { if (method.getReturnType().isArray()) { return convertToArray(result); } else { return convertToDeclaredCollection(sqlSession.getConfiguration(), result); } } return result; } /** * 獲取參數名的方法 */ public Object getNamedParams(Object[] args) { final int paramCount = names.size(); if (args == null || paramCount == 0) { //如果傳過來的參數是空 return null; } else if (!hasParamAnnotation && paramCount == 1) { //如果參數上沒有加注解例如@Param,且參數只有一個,則直接返回參數 return args[names.firstKey()]; } else { //如果參數上加了注解,或者參數有多個。 //那么MyBatis會封裝參數為一個Map,但是要注意,由於jdk的原因,我們只能獲取到參數下標和參數名,但是參數名會變成arg0,arg1. //所以傳入多個參數的時候,最好加@Param,否則假設傳入多個String,會造成#{}獲取不到值的情況 final Map<String, Object> param = new ParamMap<>(); int i = 0; for (Map.Entry<Integer, String> entry : names.entrySet()) { //entry.getValue 就是參數名稱 param.put(entry.getValue(), args[entry.getKey()]); //如果傳很多個String,也可以使用param1,param2.。。 // add generic param names (param1, param2, ...) final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1); // ensure not to overwrite parameter named with @Param if (!names.containsValue(genericParamName)) { param.put(genericParamName, args[entry.getKey()]); } i++; } return param; } }
SQL執行(二級緩存)
執行SQL的核心方法就是selectList,即使是selectOne,底層實際上也是調用了selectList方法,然后取第一個而已。
@Override public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { try { //MappedStatement:解析XML時生成的對象, 解析某一個SQL 會封裝成MappedStatement,里面存放了我們所有執行SQL所需要的信息 MappedStatement ms = configuration.getMappedStatement(statement); //查詢,通過executor 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(); } }
在這里我們又看到了上一篇構造的時候提到的,MappedStatement對象,這個對象是解析Mapper.xml配置而產生的,用於存儲SQL信息,執行SQL需要這個對象中保存的關於SQL的信息,而selectList內部調用了Executor對象執行SQL語句,這個對象作為MyBatis四大對象之一,一會會說。
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException { //獲取sql語句 BoundSql boundSql = ms.getBoundSql(parameterObject); //生成一個緩存的key //這里是-1181735286:4652640444:com.DemoMapper.selectAll:0:2147483647:select * from test WHERE id =?:2121:development 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 cache = ms.getCache(); if (cache != null) { //如果Cache不為空則進入 //如果有需要的話,就刷新緩存(有些緩存是定時刷新的,需要用到這個) flushCacheIfRequired(ms); //如果這個statement用到了緩存(二級緩存的作用域是namespace,也可以理解為這里的ms) if (ms.isUseCache() && resultHandler == null) { ensureNoOutParams(ms, boundSql); @SuppressWarnings("unchecked") //先從緩存拿 List<E> list = (List<E>) tcm.getObject(cache, key); if (list == null) { //如果緩存的數據等於空,那么查詢數據庫 list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); //查詢完畢后將數據放入二級緩存 tcm.putObject(cache, key, list); // issue #578 and #116 } //返回 return list; } } //如果cache根本就不存在,那么直接查詢一級緩存 return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); }
首先MyBatis在查詢時,不會直接查詢數據庫,而是會進行二級緩存的查詢,由於二級緩存的作用域是namespace,也可以理解為一個mapper,所以還會判斷一下這個mapper是否開啟了二級緩存,如果沒有開啟,則進入一級緩存繼續查詢。
SQL查詢(一級緩存)
//一級緩存查詢 @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 { //查詢棧+1 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 { //查詢棧-1 queryStack--; } if (queryStack == 0) { for (DeferredLoad deferredLoad : deferredLoads) { deferredLoad.load(); } // issue #601 deferredLoads.clear(); if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) { // issue #482 clearLocalCache(); } } //結果返回 return list; }
如果一級緩存查到了,那么直接就返回結果了,如果一級緩存沒有查到結果,那么最終會進入數據庫進行查詢。
SQL執行(數據庫查詢)
//數據庫查詢 private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { List<E> list; //先往一級緩存中put一個占位符 localCache.putObject(key, EXECUTION_PLACEHOLDER); try { //調用doQuery方法查詢數據庫 list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql); } finally { localCache.removeObject(key); } //往緩存中put真實數據 localCache.putObject(key, list); if (ms.getStatementType() == StatementType.CALLABLE) { localOutputParameterCache.putObject(key, parameter); } return list; } //真實數據庫查詢 @Override 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也是MyBatis四大對象之一 StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql); //#{} -> ? 的SQL在這里初始化 stmt = prepareStatement(handler, ms.getStatementLog()); //參數賦值完畢之后,才會真正地查詢。 return handler.query(stmt, resultHandler); } finally { closeStatement(stmt); } }
在真正的數據庫查詢之前,我們的語句還是這樣的:select * from test where id = ?
,所以要先將占位符換成真實的參數值,所以接下來會進行參數的賦值。
參數賦值
因為MyBatis底層封裝的就是java最基本的jdbc,所以賦值一定也是調用jdbc的putString()方法。
/********************************參數賦值部分*******************************/ //由於是#{},所以使用的是prepareStatement,預編譯SQL private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException { Statement stmt; //拿連接對象 Connection connection = getConnection(statementLog); //初始化prepareStatement stmt = handler.prepare(connection, transaction.getTimeout()); //獲取了PrepareStatement之后,這里給#{}賦值 handler.parameterize(stmt); return stmt; } /** * 預編譯SQL進行put值 */ @Override public void setParameters(PreparedStatement ps) { ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId()); //參數列表 List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); if (parameterMappings != null) { for (int i = 0; i < parameterMappings.size(); i++) { ParameterMapping parameterMapping = parameterMappings.get(i); if (parameterMapping.getMode() != ParameterMode.OUT) { Object value; //拿到xml中#{} 參數的名字 例如 #{id} propertyName==id String propertyName = parameterMapping.getProperty(); if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params value = boundSql.getAdditionalParameter(propertyName); } else if (parameterObject == null) { value = null; } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { value = parameterObject; } else { //metaObject存儲了參數名和參數值的對應關系 MetaObject metaObject = configuration.newMetaObject(parameterObject); value = metaObject.getValue(propertyName); } TypeHandler typeHandler = parameterMapping.getTypeHandler(); JdbcType jdbcType = parameterMapping.getJdbcType(); if (value == null && jdbcType == null) { jdbcType = configuration.getJdbcTypeForNull(); } try { //在這里給preparedStatement賦值,通過typeHandler,setParameter最終會調用一個叫做setNonNullParameter的方法。代碼貼在下面了。 typeHandler.setParameter(ps, i + 1, value, jdbcType); } catch (TypeException | SQLException e) { throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e); } } } } } //jdbc賦值 public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { //這里就是最最原生的jdbc的賦值了 ps.setString(i, parameter); } /********************************參數賦值部分*******************************/
正式執行
當參數賦值完畢后,SQL就可以執行了,在上文中的代碼可以看到當參數賦值完畢后,直接通過hanler.query()方法進行數據庫查詢
@Override public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException { //通過jdbc進行數據庫查詢。 PreparedStatement ps = (PreparedStatement) statement; ps.execute(); //處理結果集 resultSetHandler 也是MyBatis的四大對象之一 return resultSetHandler.handleResultSets(ps); }
可以很明顯看到,這里實際上也就是調用我們熟悉的原生jdbc對數據庫進行查詢。
執行階段總結
到這里,MyBatis的執行階段從宏觀角度看,一共完成了兩件事:
-
代理對象的生成
-
SQL的執行
而SQL的執行用了大量的篇幅來進行分析,雖然是根據一條查詢語句的主線來進行分析的,但是這么看下來一定很亂,所以這里我會話一個流程圖來幫助大家理解:
結果集處理
在SQL執行階段,MyBatis已經完成了對數據的查詢,那么現在還存在最后一個問題,那就是結果集處理,換句話來說,就是將結果集封裝成對象。在不用框架的時候我們是使用循環獲取結果集,然后通過getXXXX()方法一列一列地獲取,這種方法勞動強度太大,看看MyBatis是如何解決的。
@Override public List<Object> handleResultSets(Statement stmt) throws SQLException { ErrorContext.instance().activity("handling results").object(mappedStatement.getId()); //resultMap可以通過多個標簽指定多個值,所以存在多個結果集 final List<Object> multipleResults = new ArrayList<>(); int resultSetCount = 0; //拿到當前第一個結果集 ResultSetWrapper rsw = getFirstResultSet(stmt); //拿到所有的resultMap List<ResultMap> resultMaps = mappedStatement.getResultMaps(); //resultMap的數量 int resultMapCount = resultMaps.size(); validateResultMapsCount(rsw, resultMapCount); //循環處理每一個結果集 while (rsw != null && resultMapCount > resultSetCount) { //開始封裝結果集 list.get(index) 獲取結果集 ResultMap resultMap = resultMaps.get(resultSetCount); //傳入resultMap處理結果集 rsw 當前結果集(主線) handleResultSet(rsw, resultMap, multipleResults, null); rsw = getNextResultSet(stmt); cleanUpAfterHandlingResultSet(); resultSetCount++; } String[] resultSets = mappedStatement.getResultSets(); if (resultSets != null) { while (rsw != null && resultSetCount < resultSets.length) { ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]); if (parentMapping != null) { String nestedResultMapId = parentMapping.getNestedResultMapId(); ResultMap resultMap = configuration.getResultMap(nestedResultMapId); handleResultSet(rsw, resultMap, null, parentMapping); } rsw = getNextResultSet(stmt); cleanUpAfterHandlingResultSet(); resultSetCount++; } } //如果只有一個結果集,那么從多結果集中取出第一個 return collapseSingleResultList(multipleResults); } //處理結果集 private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException { //處理結果集 try { if (parentMapping != null) { handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping); } else { if (resultHandler == null) { //判斷resultHandler是否為空,如果為空建立一個默認的。 //結果集處理器 DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory); //處理行數據 handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null); multipleResults.add(defaultResultHandler.getResultList()); } else { handleRowValues(rsw, resultMap, resultHandler, rowBounds, null); } } } finally { // issue #228 (close resultsets) //關閉結果集 closeResultSet(rsw.getResultSet()); } }
上文的代碼,會創建一個處理結果集的對象,最終調用handleRwoValues()方法進行行數據的處理。
//處理行數據 public void handleRowValues(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException { //是否存在內嵌的結果集 if (resultMap.hasNestedResultMaps()) { ensureNoRowBounds(); checkResultHandler(); handleRowValuesForNestedResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping); } else { //不存在內嵌的結果集 handleRowValuesForSimpleResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping); } } //沒有內嵌結果集時調用 private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException { DefaultResultContext<Object> resultContext = new DefaultResultContext<>(); //獲取當前結果集 ResultSet resultSet = rsw.getResultSet(); skipRows(resultSet, rowBounds); while (shouldProcessMoreRows(resultContext, rowBounds) && !resultSet.isClosed() && resultSet.next()) { //遍歷結果集 ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(resultSet, resultMap, null); //拿到行數據,將行數據包裝成一個Object Object rowValue = getRowValue(rsw, discriminatedResultMap, null); storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet); } }
這里的代碼主要是通過每行的結果集,然后將其直接封裝成一個Object對象,那么關鍵就是在於getRowValue()方法,如何讓行數據變為Object對象的。
private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix) throws SQLException { //創建一個空的Map存值 final ResultLoaderMap lazyLoader = new ResultLoaderMap(); //創建一個空對象裝行數據 Object rowValue = createResultObject(rsw, resultMap, lazyLoader, columnPrefix); if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())){ //通過反射操作返回值 //此時metaObject.originalObject = rowValue final MetaObject metaObject = configuration.newMetaObject(rowValue); boolean foundValues = this.useConstructorMappings; if (shouldApplyAutomaticMappings(resultMap, false)) { //判斷是否需要自動映射,默認自動映射,也可以通過resultMap節點上的autoMapping配置是否自動映射 //這里是自動映射的操作。 foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, columnPrefix) || foundValues; } foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, columnPrefix) || foundValues; foundValues = lazyLoader.size() > 0 || foundValues; rowValue = foundValues || configuration.isReturnInstanceForEmptyRow() ? rowValue : null; } return rowValue; }
在getRowValue中會判斷是否是自動映射的,我們這里沒有使用ResultMap,所以是自動映射(默認),那么就進入applyAutomaticMappings()方法,而這個方法就會完成對象的封裝。
private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException { //自動映射參數列表 List<UnMappedColumnAutoMapping> autoMapping = createAutomaticMappings(rsw, resultMap, metaObject, columnPrefix); //是否找到了該列 boolean foundValues = false; if (!autoMapping.isEmpty()) { //遍歷 for (UnMappedColumnAutoMapping mapping : autoMapping) { //通過列名獲取值 final Object value = mapping.typeHandler.getResult(rsw.getResultSet(), mapping.column); if (value != null) { //如果值不為空,說明找到了該列 foundValues = true; } if (value != null || (configuration.isCallSettersOnNulls() && !mapping.primitive)) { // gcode issue #377, call setter on nulls (value is not 'found') //在這里賦值 metaObject.setValue(mapping.property, value); } } } return foundValues; }
我們可以看到這個方法會通過遍歷參數列表從而通過metaObject.setValue(mapping.property, value);
對返回對象進行賦值,但是返回對象有可能是Map,有可能是我們自定義的對象,會有什么區別呢?
實際上,所有的賦值操作在內部都是通過一個叫ObjectWrapper的對象完成的,我們可以進去看看它對於Map和自定義對象賦值的實現有什么區別,問題就迎刃而解了。
先看看上文中代碼的metaObject.setValue()
方法
public void setValue(String name, Object value) { PropertyTokenizer prop = new PropertyTokenizer(name); if (prop.hasNext()) { MetaObject metaValue = metaObjectForProperty(prop.getIndexedName()); if (metaValue == SystemMetaObject.NULL_META_OBJECT) { if (value == null) { // don't instantiate child path if value is null return; } else { metaValue = objectWrapper.instantiatePropertyValue(name, prop, objectFactory); } } metaValue.setValue(prop.getChildren(), value); } else { //這個方法最終會調用objectWrapper.set()對結果進行賦值 objectWrapper.set(prop, value); } }
我們可以看看objectWrapper的實現類:
而我們今天舉的例子,DemoMapper的返回值是Map,所以objectWrapper會調用MapWrapper的set方法,如果是自定義類型,那么就會調用BeanWrapper的set方法,下面看看兩個類中的set方法有什么區別:
//MapWrapper的set方法 public void set(PropertyTokenizer prop, Object value) { if (prop.getIndex() != null) { Object collection = resolveCollection(prop, map); setCollectionValue(prop, collection, value); } else { //實際上就是調用了Map的put方法將屬性名和屬性值放入map中 map.put(prop.getName(), value); } } //BeanWrapper的set方法 public void set(PropertyTokenizer prop, Object value) { if (prop.getIndex() != null) { Object collection = resolveCollection(prop, object); setCollectionValue(prop, collection, value); } else { //在這里賦值,通過反射賦值,調用setXX()方法賦值 setBeanProperty(prop, object, value); } } private void setBeanProperty(PropertyTokenizer prop, Object object, Object value) { try { Invoker method = metaClass.getSetInvoker(prop.getName()); Object[] params = {value}; try { method.invoke(object, params); } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } } catch (Throwable t) { throw new ReflectionException("Could not set property '" + prop.getName() + "' of '" + object.getClass() + "' with value '" + value + "' Cause: " + t.toString(), t); } }
上面兩個set方法分別是MapWrapper和BeanWrapper的不同實現,MapWrapper的set方法實際上就是將屬性名和屬性值放到map的key和value中,而BeanWrapper則是使用了反射,調用了Bean的set方法,將值注入。
結語
至此,MyBatis的執行流程就為止了,本篇主要聊了從構建配置對象后,MyBatis是如何執行一條查詢語句的,一級查詢語句結束后是如何進行對結果集進行處理,映射為我們定義的數據類型的。
由於是源碼分析文章,所以如果只是粗略的看,會顯得有些亂,所以我還是再提供一張流程圖,會比較好理解一些。
當然這張流程圖里並沒有涉及到關於回寫緩存的內容,關於MyBatis的一級緩存、二級緩存相關的內容,我會在第三篇源碼解析中闡述。