前言
上一篇文章《MyBatis源碼解析(一)—構(gòu)造篇》提到了MyBatis是如何構(gòu)建配置類的斩箫,也說了MyBatis在運(yùn)行過程中主要分為兩個階段吏砂,第一是構(gòu)建,第二就是執(zhí)行乘客,所以這篇文章會帶大家來了解一下MyBatis是如何從構(gòu)建完畢狐血,到執(zhí)行我們的第一條SQL語句的。
入口(代理對象的生成)
public static void main(String[] args) throws Exception {
/******************************構(gòu)造******************************/
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//創(chuàng)建SqlSessionFacory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
/******************************分割線******************************/
/******************************執(zhí)行******************************/
//SqlSession是幫我們操作數(shù)據(jù)庫的對象
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進(jìn)行整合)匈织,操作SQL的只需要一個對象,那就是SqlSession對象牡直,這個對象就是專門與數(shù)據(jù)庫進(jìn)行交互的缀匕。
我們在構(gòu)造篇有提到,Configuration對象是在SqlSessionFactoryBuilder中的build方法中調(diào)用了XMLConfigBuilder的parse方法進(jìn)行解析的碰逸,但是我們沒有提到這個Configuration最終的去向乡小。講這個之前我們可以思考一下,這個Configuration生成之后饵史,會在哪個環(huán)節(jié)被使用满钟?毋庸置疑胜榔,它作為一個配置文件的整合,里面包含了數(shù)據(jù)庫連接相關(guān)的信息湃番,SQL語句相關(guān)信息等夭织,在查詢的整個流程中必不可少,而剛才我們又說過吠撮,SqlSession實(shí)際上是我們操作數(shù)據(jù)庫的一個真實(shí)對象摔癣,所以可以得出這個結(jié)論:Configuration必然和SqlSession有所聯(lián)系。
源碼:
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里面的節(jié)點(diǎn)
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;
}
實(shí)際上我們從源碼中可以看到纬向,Configuration是SqlSessionFactory的一個屬性择浊,而SqlSessionFactoryBuilder在build方法中實(shí)際上就是調(diào)用XMLConfigBuilder對xml文件進(jìn)行解析,然后注入到SqlSessionFactory中逾条。
明確了這一點(diǎn)我們就接著往下看琢岩。
根據(jù)主線我們現(xiàn)在得到了一個SqlSessionFactory對象,下一步就是要去獲取SqlSession對象师脂,這里會調(diào)用SqlSessionFactory.openSession()方法來獲取担孔,而openSession中實(shí)際上就是對SqlSession做了進(jìn)一步的加工封裝,包括增加了事務(wù)吃警、執(zhí)行器等糕篇。
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
//對SqlSession對象進(jìn)行進(jìn)一步加工封裝
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
final Executor executor = configuration.newExecutor(tx, execType);
//構(gòu)建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();
}
}
到這里可以得出的小結(jié)論是,SqlSessionFactory對象中由于存在Configuration對象酌心,所以它保存了全局配置信息拌消,以及初始化環(huán)境和DataSource,而DataSource的作用就是用來開辟鏈接安券,當(dāng)我們調(diào)用openSession方法時墩崩,就會開辟一個連接對象并傳給SqlSession對象,交給SqlSession來對數(shù)據(jù)庫做相關(guān)操作侯勉。
接著往下鹦筹,現(xiàn)在我們獲取到了一個SqlSession對象,而執(zhí)行過程就是從這里開始的址貌。
我們可以開始回憶了铐拐,平時我們使用MyBatis的時候,我們寫的DAO層應(yīng)該長這樣:
public interface DemoMapper {
public List<Map<String,Object>> selectAll(Map<String,Object> map);
}
實(shí)際上它是一個接口练对,而且并沒有實(shí)現(xiàn)類遍蟋,而我們卻可以直接對它進(jìn)行調(diào)用,如下:
DemoMapper mapper = sqlSession.getMapper(DemoMapper.class);
Map<String,Object> map = new HashMap();
map.put("id","123");
System.out.println(mapper.selectAll(map));
可以猜測了锹淌,MyBatis底層一定使用了動態(tài)代理匿值,來對這個接口進(jìn)行代理,我們實(shí)際上調(diào)用的是MyBatis為我們生成的代理對象赂摆。
我們在獲取Mapper的時候挟憔,需要調(diào)用SqlSession的getMapper()方法钟些,那么就從這里深入。
//getMapper方法最終會調(diào)用到這里绊谭,這個是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是在什么時候生成的呢宗弯?實(shí)際上這是我上一篇漏講的一個地方,在解析的時候搂妻,會調(diào)用parse()方法,相信大家都還記得蒙保,這個方法內(nèi)部有一個bindMapperForNamespace方法,而就是這個方法幫我們完成了knownMappers的生成欲主,并且將我們的Mapper接口put進(jìn)去邓厕。
public void parse() {
//判斷文件是否之前解析過
if (!configuration.isResourceLoaded(resource)) {
//解析mapper文件
configurationElement(parser.evalNode("/mapper"));
configuration.addLoadedResource(resource);
//這里:綁定Namespace里面的Class對象*
bindMapperForNamespace();
}
//重新解析之前解析不了的節(jié)點(diǎn)
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進(jìn)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详恼,之后的代碼就簡單了,就是生成標(biāo)準(zhǔn)的代理類了引几,調(diào)用newInstance()方法昧互。
public T newInstance(SqlSession sqlSession) {
//首先會調(diào)用這個newInstance方法
//動態(tài)代理邏輯在MapperProxy里面
final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
//通過這里調(diào)用下面的newInstance方法
return newInstance(mapperProxy);
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
//jdk自帶的動態(tài)代理
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
到這里,就完成了代理對象(MapperProxy)的創(chuàng)建她紫,很明顯的硅堆,MyBatis的底層就是對我們的接口進(jìn)行代理類的實(shí)例化屿储,從而操作數(shù)據(jù)庫贿讹。
但是,我們好像就得到了一個空蕩蕩的對象够掠,調(diào)用方法的邏輯呢民褂?好像根本就沒有看到,所以這也是比較考驗(yàn)Java功底的地方疯潭。
我們知道赊堪,一個類如果要稱為代理對象,那么一定需要實(shí)現(xiàn)InvocationHandler接口竖哩,并且實(shí)現(xiàn)其中的invoke方法哭廉,進(jìn)行一波推測,邏輯一定在invoke方法中相叁。
于是就可以點(diǎn)進(jìn)MapperProxy類遵绰,發(fā)現(xiàn)其的確實(shí)現(xiàn)了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) {
//構(gòu)造
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//這就是一個很標(biāo)準(zhǔn)的JDK動態(tài)代理了
//執(zhí)行的時候會調(diào)用invoke方法
try {
if (Object.class.equals(method.getDeclaringClass())) {
//判斷方法所屬的類
//是不是調(diào)用的Object默認(rèn)的方法
//如果是 則不代理乌企,不改變原先方法的行為
return method.invoke(this, args);
} else if (method.isDefault()) {
//對于默認(rèn)方法的處理
//判斷是否為default方法,即接口中定義的默認(rèn)方法成玫。
//如果是接口中的默認(rèn)方法則把方法綁定到代理對象中然后調(diào)用加酵。
//這里不詳細(xì)說
if (privateLookupInMethod == null) {
return invokeDefaultMethodJava8(proxy, method, args);
} else {
return invokeDefaultMethodJava9(proxy, method, args);
}
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
//如果不是默認(rèn)方法,則真正開始執(zhí)行MyBatis代理邏輯哭当。
//獲取MapperMethod代理對象
final MapperMethod mapperMethod = cachedMapperMethod(method);
//執(zhí)行
return mapperMethod.execute(sqlSession, args);
}
private MapperMethod cachedMapperMethod(Method method) {
//動態(tài)代理會有緩存猪腕,computeIfAbsent 如果緩存中有則直接從緩存中拿
//如果緩存中沒有,則new一個然后放入緩存中
//因?yàn)閯討B(tài)代理是很耗資源的
return methodCache.computeIfAbsent(method,
k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
}
}
在方法開始代理之前钦勘,首先會先判斷是否調(diào)用了Object類的方法码撰,如果是,那么MyBatis不會去改變其行為个盆,直接返回脖岛,如果是默認(rèn)方法,則綁定到代理對象中然后調(diào)用(不是本文的重點(diǎn))颊亮,如果都不是柴梆,那么就是我們定義的mapper接口方法了,那么就開始執(zhí)行终惑。
執(zhí)行方法需要一個MapperMethod對象绍在,這個對象是MyBatis執(zhí)行方法邏輯使用的,MyBatis這里獲取MapperMethod對象的方式是雹有,首先去方法緩存中看看是否已經(jīng)存在了偿渡,如果不存在則new一個然后存入緩存中,因?yàn)閯?chuàng)建代理對象是十分消耗資源的操作霸奕×锟恚總而言之,這里會得到一個MapperMethod對象质帅,然后通過MapperMethod的excute()方法适揉,來真正地執(zhí)行邏輯。
執(zhí)行邏輯
-
語句類型判斷
這里首先會判斷SQL的類型:SELECT|DELETE|UPDATE|INSERT煤惩,我們這里舉的例子是SELECT嫉嘀,其它的其實(shí)都差不多,感興趣的同學(xué)可以自己去看看魄揉。判斷SQL類型為SELECT之后剪侮,就開始判斷返回值類型,根據(jù)不同的情況做不同的操作洛退。然后開始獲取參數(shù)--》執(zhí)行SQL瓣俯。
//execute() 這里是真正執(zhí)行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()) { //返回值多行 這里調(diào)用這個方法 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; } //返回值多行 這里調(diào)用這個方法 private <E> Object executeForMany(SqlSession sqlSession, Object[] args) { //返回值多行時執(zhí)行的方法 List<E> result; //param是我們傳入的參數(shù)红淡,如果傳入的是Map,那么這個實(shí)際上就是Map對象 Object param = method.convertArgsToSqlCommandParam(args); if (method.hasRowBounds()) { //如果有分頁 RowBounds rowBounds = method.extractRowBounds(args); //執(zhí)行SQL的位置 result = sqlSession.selectList(command.getName(), param, rowBounds); } else { //如果沒有 //執(zhí)行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; } /** * 獲取參數(shù)名的方法 */ public Object getNamedParams(Object[] args) { final int paramCount = names.size(); if (args == null || paramCount == 0) { //如果傳過來的參數(shù)是空 return null; } else if (!hasParamAnnotation && paramCount == 1) { //如果參數(shù)上沒有加注解例如@Param降铸,且參數(shù)只有一個在旱,則直接返回參數(shù) return args[names.firstKey()]; } else { //如果參數(shù)上加了注解,或者參數(shù)有多個推掸。 //那么MyBatis會封裝參數(shù)為一個Map桶蝎,但是要注意,由于jdk的原因谅畅,我們只能獲取到參數(shù)下標(biāo)和參數(shù)名登渣,但是參數(shù)名會變成arg0,arg1. //所以傳入多個參數(shù)的時候,最好加@Param毡泻,否則假設(shè)傳入多個String胜茧,會造成#{}獲取不到值的情況 final Map<String, Object> param = new ParamMap<>(); int i = 0; for (Map.Entry<Integer, String> entry : names.entrySet()) { //entry.getValue 就是參數(shù)名稱 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執(zhí)行(二級緩存)
執(zhí)行SQL的核心方法就是selectList丹墨,即使是selectOne廊遍,底層實(shí)際上也是調(diào)用了selectList方法,然后取第一個而已贩挣。
@Override public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { try { //MappedStatement:解析XML時生成的對象喉前, 解析某一個SQL 會封裝成MappedStatement,里面存放了我們所有執(zhí)行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(); } }
在這里我們又看到了上一篇構(gòu)造的時候提到的王财,MappedStatement對象卵迂,這個對象是解析Mapper.xml配置而產(chǎn)生的,用于存儲SQL信息绒净,執(zhí)行SQL需要這個對象中保存的關(guān)于SQL的信息见咒,而selectList內(nèi)部調(diào)用了Executor對象執(zhí)行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不為空則進(jìn)入 //如果有需要的話,就刷新緩存(有些緩存是定時刷新的囱嫩,需要用到這個) 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) { //如果緩存的數(shù)據(jù)等于空漏设,那么查詢數(shù)據(jù)庫 list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); //查詢完畢后將數(shù)據(jù)放入二級緩存 tcm.putObject(cache, key, list); // issue #578 and #116 } //返回 return list; } } //如果cache根本就不存在墨闲,那么直接查詢一級緩存 return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); }
首先MyBatis在查詢時,不會直接查詢數(shù)據(jù)庫郑口,而是會進(jìn)行二級緩存的查詢鸳碧,由于二級緩存的作用域是namespace盾鳞,也可以理解為一個mapper,所以還會判斷一下這個mapper是否開啟了二級緩存瞻离,如果沒有開啟腾仅,則進(jìn)入一級緩存繼續(xù)查詢。
-
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 { //如果緩存為空套利,則從數(shù)據(jù)庫拿 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(); } } //結(jié)果返回 return list; }
如果一級緩存查到了推励,那么直接就返回結(jié)果了,如果一級緩存沒有查到結(jié)果肉迫,那么最終會進(jìn)入數(shù)據(jù)庫進(jìn)行查詢验辞。
-
SQL執(zhí)行(數(shù)據(jù)庫查詢)
//數(shù)據(jù)庫查詢 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 { //調(diào)用doQuery方法查詢數(shù)據(jù)庫 list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql); } finally { localCache.removeObject(key); } //往緩存中put真實(shí)數(shù)據(jù) localCache.putObject(key, list); if (ms.getStatementType() == StatementType.CALLABLE) { localOutputParameterCache.putObject(key, parameter); } return list; } //真實(shí)數(shù)據(jù)庫查詢 @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()); //參數(shù)賦值完畢之后喊衫,才會真正地查詢跌造。 return handler.query(stmt, resultHandler); } finally { closeStatement(stmt); } }
在真正的數(shù)據(jù)庫查詢之前,我們的語句還是這樣的:
select * from test where id = ?
族购,所以要先將占位符換成真實(shí)的參數(shù)值壳贪,所以接下來會進(jìn)行參數(shù)的賦值。-
參數(shù)賦值
因?yàn)镸yBatis底層封裝的就是java最基本的jdbc寝杖,所以賦值一定也是調(diào)用jdbc的putString()方法撑碴。
/********************************參數(shù)賦值部分*******************************/ //由于是#{},所以使用的是prepareStatement朝墩,預(yù)編譯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; } /** * 預(yù)編譯SQL進(jìn)行put值 */ @Override public void setParameters(PreparedStatement ps) { ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId()); //參數(shù)列表 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中#{} 參數(shù)的名字 例如 #{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存儲了參數(shù)名和參數(shù)值的對應(yīng)關(guān)系 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最終會調(diào)用一個叫做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); } /********************************參數(shù)賦值部分*******************************/
-
正式執(zhí)行
當(dāng)參數(shù)賦值完畢后鹿霸,SQL就可以執(zhí)行了排吴,在上文中的代碼可以看到當(dāng)參數(shù)賦值完畢后,直接通過hanler.query()方法進(jìn)行數(shù)據(jù)庫查詢懦鼠。
@Override public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException { //通過jdbc進(jìn)行數(shù)據(jù)庫查詢钻哩。 PreparedStatement ps = (PreparedStatement) statement; ps.execute(); //處理結(jié)果集 resultSetHandler 也是MyBatis的四大對象之一 return resultSetHandler.handleResultSets(ps); }
可以很明顯看到,這里實(shí)際上也就是調(diào)用我們熟悉的原生jdbc對數(shù)據(jù)庫進(jìn)行查詢肛冶。
-
-
執(zhí)行階段總結(jié)
到這里街氢,MyBatis的執(zhí)行階段從宏觀角度看,一共完成了兩件事:
- 代理對象的生成
- SQL的執(zhí)行
而SQL的執(zhí)行用了大量的篇幅來進(jìn)行分析睦袖,雖然是根據(jù)一條查詢語句的主線來進(jìn)行分析的珊肃,但是這么看下來一定很亂,所以這里我會話一個流程圖來幫助大家理解:
執(zhí)行階段流程圖 -
結(jié)果集處理
在SQL執(zhí)行階段,MyBatis已經(jīng)完成了對數(shù)據(jù)的查詢伦乔,那么現(xiàn)在還存在最后一個問題厉亏,那就是結(jié)果集處理,換句話來說烈和,就是將結(jié)果集封裝成對象爱只。在不用框架的時候我們是使用循環(huán)獲取結(jié)果集,然后通過getXXXX()方法一列一列地獲取招刹,這種方法勞動強(qiáng)度太大恬试,看看MyBatis是如何解決的。
@Override public List<Object> handleResultSets(Statement stmt) throws SQLException { ErrorContext.instance().activity("handling results").object(mappedStatement.getId()); //resultMap可以通過多個標(biāo)簽指定多個值蔗喂,所以存在多個結(jié)果集 final List<Object> multipleResults = new ArrayList<>(); int resultSetCount = 0; //拿到當(dāng)前第一個結(jié)果集 ResultSetWrapper rsw = getFirstResultSet(stmt); //拿到所有的resultMap List<ResultMap> resultMaps = mappedStatement.getResultMaps(); //resultMap的數(shù)量 int resultMapCount = resultMaps.size(); validateResultMapsCount(rsw, resultMapCount); //循環(huán)處理每一個結(jié)果集 while (rsw != null && resultMapCount > resultSetCount) { //開始封裝結(jié)果集 list.get(index) 獲取結(jié)果集 ResultMap resultMap = resultMaps.get(resultSetCount); //傳入resultMap處理結(jié)果集 rsw 當(dāng)前結(jié)果集(主線) 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++; } } //如果只有一個結(jié)果集忘渔,那么從多結(jié)果集中取出第一個 return collapseSingleResultList(multipleResults); } //處理結(jié)果集 private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException { //處理結(jié)果集 try { if (parentMapping != null) { handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping); } else { if (resultHandler == null) { //判斷resultHandler是否為空,如果為空建立一個默認(rèn)的缰儿。 //結(jié)果集處理器 DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory); //處理行數(shù)據(jù) handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null); multipleResults.add(defaultResultHandler.getResultList()); } else { handleRowValues(rsw, resultMap, resultHandler, rowBounds, null); } } } finally { // issue #228 (close resultsets) //關(guān)閉結(jié)果集 closeResultSet(rsw.getResultSet()); } }
上文的代碼畦粮,會創(chuàng)建一個處理結(jié)果集的對象,最終調(diào)用handleRwoValues()方法進(jìn)行行數(shù)據(jù)的處理乖阵。
//處理行數(shù)據(jù) public void handleRowValues(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException { //是否存在內(nèi)嵌的結(jié)果集 if (resultMap.hasNestedResultMaps()) { ensureNoRowBounds(); checkResultHandler(); handleRowValuesForNestedResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping); } else { //不存在內(nèi)嵌的結(jié)果集 handleRowValuesForSimpleResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping); } } //沒有內(nèi)嵌結(jié)果集時調(diào)用 private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException { DefaultResultContext<Object> resultContext = new DefaultResultContext<>(); //獲取當(dāng)前結(jié)果集 ResultSet resultSet = rsw.getResultSet(); skipRows(resultSet, rowBounds); while (shouldProcessMoreRows(resultContext, rowBounds) && !resultSet.isClosed() && resultSet.next()) { //遍歷結(jié)果集 ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(resultSet, resultMap, null); //拿到行數(shù)據(jù)宣赔,將行數(shù)據(jù)包裝成一個Object Object rowValue = getRowValue(rsw, discriminatedResultMap, null); storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet); } }
這里的代碼主要是通過每行的結(jié)果集,然后將其直接封裝成一個Object對象瞪浸,那么關(guān)鍵就是在于getRowValue()方法儒将,如何讓行數(shù)據(jù)變?yōu)镺bject對象的。
private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix) throws SQLException { //創(chuàng)建一個空的Map存值 final ResultLoaderMap lazyLoader = new ResultLoaderMap(); //創(chuàng)建一個空對象裝行數(shù)據(jù) 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)) { //判斷是否需要自動映射对蒲,默認(rèn)自動映射钩蚊,也可以通過resultMap節(jié)點(diǎn)上的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砰逻,所以是自動映射(默認(rèn)),那么就進(jìn)入applyAutomaticMappings()方法泛鸟,而這個方法就會完成對象的封裝蝠咆。
private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException { //自動映射參數(shù)列表 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; }
我們可以看到這個方法會通過遍歷參數(shù)列表從而通過
metaObject.setValue(mapping.property, value);
對返回對象進(jìn)行賦值北滥,但是返回對象有可能是Map刚操,有可能是我們自定義的對象,會有什么區(qū)別呢再芋?實(shí)際上菊霜,所有的賦值操作在內(nèi)部都是通過一個叫ObjectWrapper的對象完成的,我們可以進(jìn)去看看它對于Map和自定義對象賦值的實(shí)現(xiàn)有什么區(qū)別祝闻,問題就迎刃而解了占卧。
先看看上文中代碼的
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 { //這個方法最終會調(diào)用objectWrapper.set()對結(jié)果進(jìn)行賦值 objectWrapper.set(prop, value); } }
我們可以看看objectWrapper的實(shí)現(xiàn)類:
objectWrapper的實(shí)現(xiàn)類而我們今天舉的例子遗菠,DemoMapper的返回值是Map联喘,所以objectWrapper會調(diào)用MapWrapper的set方法华蜒,如果是自定義類型,那么就會調(diào)用BeanWrapper的set方法豁遭,下面看看兩個類中的set方法有什么區(qū)別:
//MapWrapper的set方法 public void set(PropertyTokenizer prop, Object value) { if (prop.getIndex() != null) { Object collection = resolveCollection(prop, map); setCollectionValue(prop, collection, value); } else { //實(shí)際上就是調(diào)用了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 { //在這里賦值叭喜,通過反射賦值,調(diào)用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的不同實(shí)現(xiàn)蓖谢,MapWrapper的set方法實(shí)際上就是將屬性名和屬性值放到map的key和value中捂蕴,而BeanWrapper則是使用了反射,調(diào)用了Bean的set方法闪幽,將值注入啥辨。
反射注入
結(jié)語
至此,MyBatis的執(zhí)行流程就為止了盯腌,本篇主要聊了從構(gòu)建配置對象后溉知,MyBatis是如何執(zhí)行一條查詢語句的,一級查詢語句結(jié)束后是如何進(jìn)行對結(jié)果集進(jìn)行處理腕够,映射為我們定義的數(shù)據(jù)類型的级乍。
由于是源碼分析文章,所以如果只是粗略的看帚湘,會顯得有些亂玫荣,所以我還是再提供一張流程圖,會比較好理解一些大诸。
當(dāng)然這張流程圖里并沒有涉及到關(guān)于回寫緩存的內(nèi)容捅厂,關(guān)于MyBatis的一級緩存、二級緩存相關(guān)的內(nèi)容资柔,我會在第三篇源碼解析中闡述焙贷。
歡迎大家訪問我的個人博客:Object's Blog