上一篇文章提到了MyBatis是如何構建配置類的,也說了MyBatis在運行過程當中主要分爲兩個階段,第一是構建,第二就是執行,因此這篇文章會帶你們來了解一下MyBatis是如何從構建完畢,到執行咱們的第一條SQL語句的。以後這部份內容會歸置到公衆號菜單欄:連載中…-框架分析中,歡迎探討!html
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對象,這個對象就是專門與數據庫進行交互的。java
咱們在構造篇有提到,Configuration對象是在SqlSessionFactoryBuilder中的build方法中調用了XMLConfigBuilder的parse方法進行解析的,可是咱們沒有提到這個Configuration最終的去向。講這個以前咱們能夠思考一下,這個Configuration生成以後,會在哪一個環節被使用?毋庸置疑,它做爲一個配置文件的整合,裏面包含了數據庫鏈接相關的信息,SQL語句相關信息等,在查詢的整個流程中必不可少,而剛纔咱們又說過,SqlSession其實是咱們操做數據庫的一個真實對象,因此能夠得出這個結論:Configuration必然和SqlSession有所聯繫。sql
源碼:數據庫
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中。緩存
明確了這一點咱們就接着往下看。session
根據主線咱們如今獲得了一個SqlSessionFactory對象,下一步就是要去獲取SqlSession對象,這裏會調用SqlSessionFactory.openSession()方法來獲取,而openSession中實際上就是對SqlSession作了進一步的加工封裝,包括增長了事務、執行器等。mybatis
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來對數據庫作相關操做。app
接着往下,如今咱們獲取到了一個SqlSession對象,而執行過程就是從這裏開始的。框架
咱們能夠開始回憶了,平時咱們使用MyBatis的時候,咱們寫的DAO層應該長這樣:dom
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的核心方法就是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是否開啓了二級緩存,若是沒有開啓,則進入一級緩存繼續查詢。
//一級緩存查詢 @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; }
若是一級緩存查到了,那麼直接就返回結果了,若是一級緩存沒有查到結果,那麼最終會進入數據庫進行查詢。
//數據庫查詢 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的一級緩存、二級緩存相關的內容,我會在第三篇源碼解析中闡述。
原文出處:https://www.cnblogs.com/javazhiyin/p/12344651.html