本文將按mybatis中主要數(shù)據(jù)庫(kù)查詢操作的流程對(duì)其源碼進(jìn)行簡(jiǎn)單分析。目錄如下:
1、mybatis的主要工作流程
2、mybatis進(jìn)行數(shù)據(jù)查詢的小實(shí)例
3、源碼分析
3.1、獲取SqlSessionFactory(配置文件解析)
3.2、Mapper對(duì)象獲取
3.3、Mapper方法執(zhí)行
4、總結(jié)
1、mybatis的主要工作流程
mybatis的工作流程:
加載配置-->SQL解析-->SQL執(zhí)行-->結(jié)果映射
加載配置:配置來(lái)源于兩個(gè)地方,一處是配置文件,一處是Java代碼的注解,將SQL的配置信息加載成為一個(gè)個(gè)MappedStatement對(duì)象(包括了傳入?yún)?shù)映射配置、執(zhí)行的SQL語(yǔ)句、結(jié)果映射配置),存儲(chǔ)在內(nèi)存中。
SQL解析:當(dāng)API接口層接收到調(diào)用請(qǐng)求時(shí),會(huì)接收到傳入SQL的ID和傳入對(duì)象(可以是Map、JavaBean或者基本數(shù)據(jù)類型),Mybatis會(huì)根據(jù)SQL的ID找到對(duì)應(yīng)的MappedStatement,然后根據(jù)傳入?yún)?shù)對(duì)象對(duì)MappedStatement進(jìn)行解析,解析后可以得到最終要執(zhí)行的SQL語(yǔ)句和參數(shù)。
SQL執(zhí)行:將最終得到的SQL和參數(shù)拿到數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行,得到操作數(shù)據(jù)庫(kù)的結(jié)果。
結(jié)果映射:將操作數(shù)據(jù)庫(kù)的結(jié)果按照映射的配置進(jìn)行轉(zhuǎn)換,可以轉(zhuǎn)換成HashMap、JavaBean或者基本數(shù)據(jù)類型,并將最終結(jié)果返回
后面將按這個(gè)步驟來(lái)注解分析源碼.
2、mybatis進(jìn)行數(shù)據(jù)查詢的小實(shí)例
下面代碼主要展示了mybatis中進(jìn)行數(shù)據(jù)庫(kù)操作的幾個(gè)核心要素。
public void testFindUserById(int userId) throws IOException {
// mybatis配置文件
String resource = "mybatis-config.xml";
// mybatis通過(guò)SqlSessionFactory獲取SessionFactory
// 然后獲取SqlSession,通過(guò)sqlSession來(lái)獲取映射執(zhí)行SQL的。
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));;
SqlSession sqlSession = null;
if (sf != null) {
sqlSession = getSqlSessionFactory().openSession();
SysUserDao userDao = sqlSession.getMapper(SysUserDao.class);
SysUser user = userDao.findUserById(userId);
}
}
通過(guò)配置文件,生成了SqlSessionFactory,從而創(chuàng)建 SqlSession,在mybatis中,所有的sql執(zhí)行,都是通過(guò)SqlSession來(lái)實(shí)現(xiàn)的。
獲取到sqlSession對(duì)象后,即可通過(guò)對(duì)應(yīng)的getMapper方法來(lái)獲取接口的動(dòng)態(tài)實(shí)現(xiàn)類了,從而完成接口方法的執(zhí)行。
3、源碼分析
本節(jié)開(kāi)始,將按照上面的代碼執(zhí)行過(guò)程,對(duì)mybatis的源碼進(jìn)行分析。分析涉及到以下幾個(gè)大的過(guò)程:
- 1、對(duì)配置文件的解析。需要搞明白配置文件中的數(shù)據(jù)解析存儲(chǔ)到哪兒了
- 2、接口類實(shí)現(xiàn)的獲取。由于mybatis中是通過(guò)接口定義方法+xml配置方式來(lái)完成對(duì)數(shù)據(jù)庫(kù)的操作,核心是通過(guò)動(dòng)態(tài)代理的方式來(lái)構(gòu)造接口實(shí)現(xiàn)類的,對(duì)這個(gè)獲取過(guò)程和方法的執(zhí)行需要分析。
- 3、接口類中的方法的執(zhí)行。同上
3.1、獲取SqlSessionFactory(配置文件解析)
配置文件的解析過(guò)程,實(shí)際上是通過(guò)獲取SqlSessionFactory來(lái)實(shí)現(xiàn)的,這個(gè)過(guò)程看下圖:

在前面的例子中有一行代碼:
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));;
調(diào)用SqlSessionFactoryBuilder().build方法來(lái)創(chuàng)建sqlSession工廠,builder方法的入口參數(shù)是Reader,通過(guò)調(diào)用Resources.getResourceAsReader(resource)來(lái)實(shí)現(xiàn)的。
mybatis中的Resources類主要是通過(guò)類加載器來(lái)簡(jiǎn)化對(duì)各種資源的獲取操作
SqlSessionFactoryBuilder類主要提供了基于Reader和InputStream來(lái)解析xml文件的方法,主要依賴于XMLConfigBuilder來(lái)實(shí)現(xiàn),通過(guò)XMLConfigBuilder的parse方法解析xml配置文件得到Configuration對(duì)象,通過(guò)configuration對(duì)象構(gòu)造默認(rèn)的SqlFactory實(shí)現(xiàn)類DefaultSqlSessionFactory實(shí)例
SqlSessionFactoryBuilder的build方法最終調(diào)用到以下方法:
/**
* 解析xml文件兩個(gè)步驟:
* 1、讀取xml信息;
* 2、根據(jù)xml信息構(gòu)建SqlSession工廠
*/
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
logger.info("build init.");
// 1. 通過(guò)XMLConfigBuilder來(lái)解析xml配置文件
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
// 2. 調(diào)用xml解析器進(jìn)行解析得到Configuration對(duì)象,xml文件中的配置信息都存儲(chǔ)到configuration對(duì)象中了
// 3. 創(chuàng)建defaultSessionFactory對(duì)象
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
創(chuàng)建SelSessionFactory對(duì)象
// 創(chuàng)建SelSessionFactory對(duì)象
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
實(shí)際上,創(chuàng)建SessionFactory對(duì)象的過(guò)程分為以下3大步驟:
- 通過(guò)XMLConfigBuilder來(lái)解析xml配置文件
- 調(diào)用xml解析器進(jìn)行解析得到Configuration對(duì)象
- 創(chuàng)建defaultSessionFactory對(duì)象
// 進(jìn)行解析操作 將最終解析到的數(shù)據(jù)存儲(chǔ)在configuration對(duì)象中
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
// 從根節(jié)點(diǎn)configuration上開(kāi)始解析
parseConfiguration(parser.evalNode("/configuration"));
// 這個(gè)地方的configuration是在當(dāng)前類XMLConfigBuilder的父類BaseBuilder中定義的,在本類的構(gòu)造方法中創(chuàng)建
// 這兒configuration對(duì)象已經(jīng)返回了,通過(guò)上面的代碼可以構(gòu)造出SqlSessionFactory的實(shí)現(xiàn)對(duì)象了。
return configuration;
}
接下來(lái),在parseConfiguration方法中開(kāi)始xml文件的解析:
// 解析configuration節(jié)點(diǎn)下的配置,可對(duì)照mybatis-config.xml文件
private void parseConfiguration(XNode root) {
try {
// 提取settings
Properties settings = settingsAsPropertiess(root.evalNode("settings")); // 解析settings
//issue #117 read properties first
propertiesElement(root.evalNode("properties")); // 解析properties
loadCustomVfs(settings);
// 別名解析
typeAliasesElement(root.evalNode("typeAliases"));
// 插件解析
pluginElement(root.evalNode("plugins"));
// 解析自定義的ObjectFatory實(shí)現(xiàn)
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectionFactoryElement(root.evalNode("reflectionFactory"));
// 解析settings
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
// 解析environments 數(shù)據(jù)源的配置
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
// 類型處理解析
typeHandlerElement(root.evalNode("typeHandlers"));
// mappers映射解析
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
上面的代碼中開(kāi)始對(duì)配置文件中的各個(gè)節(jié)點(diǎn)進(jìn)行解析,我們目前關(guān)注mapper的解析即可:
private void mapperElement(XNode parent) throws Exception {
logger.info("開(kāi)始解析Mappers節(jié)點(diǎn)");
if (parent != null) {
for (XNode child : parent.getChildren()) {
if ("package".equals(child.getName())) {
logger.info("開(kāi)始處理package節(jié)點(diǎn)");
String mapperPackage = child.getStringAttribute("name");
// 調(diào)用configuration的添加方法
configuration.addMappers(mapperPackage);
} else {
// 通常將在另外的配置文件中配置SQL
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
if (resource != null && url == null && mapperClass == null) {
// <mapper resource="com/xxxxxxx/dao/****Mapper.xml"/>
logger.info("解析resource:" + resource);
ErrorContext.instance().resource(resource);
// 獲取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
// 解析器進(jìn)行解析
mapperParser.parse();
} else if (resource == null && url != null && mapperClass == null) {
// url方式解析
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url == null && mapperClass != null) {
Class<?> mapperInterface = Resources.classForName(mapperClass);
configuration.addMapper(mapperInterface);
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
logger.info("解析Mappers節(jié)點(diǎn)結(jié)束!");
}
在xml中配置了如下的mapper:
<mapper resource="com/xxxxxxx/dao/****Mapper.xml"/>,通過(guò)resource定位到指定的配置文件中,再進(jìn)行解析,XMLMapperBuilder中parse方法如下:
public void parse() {
logger.info(" 開(kāi)始解析mapper文件:XMLMapperBuilder.parse");
if (!configuration.isResourceLoaded(resource)) {
// 對(duì)mapper文件中對(duì)各個(gè)元素進(jìn)行解析
configurationElement(parser.evalNode("/mapper"));
configuration.addLoadedResource(resource);
bindMapperForNamespace();
}
parsePendingResultMaps();
parsePendingChacheRefs();
parsePendingStatements();
}
private void configurationElement(XNode context) {
try {
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.equals("")) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
logger.info("解析到mapper文件中的namespace元素:" + namespace);
builderAssistant.setCurrentNamespace(namespace);
cacheRefElement(context.evalNode("cache-ref"));
cacheElement(context.evalNode("cache"));
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
resultMapElements(context.evalNodes("/mapper/resultMap"));
sqlElement(context.evalNodes("/mapper/sql"));
// 解析配置文件中的sql語(yǔ)句,重點(diǎn)關(guān)注這兒
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
} catch (Exception e) {
throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
}
}
重點(diǎn)看對(duì)sql的解析
private void buildStatementFromContext(List<XNode> list) {
logger.info("解析mapper文件中insert | delete | update | select 元素");
if (configuration.getDatabaseId() != null) {
buildStatementFromContext(list, configuration.getDatabaseId());
}
buildStatementFromContext(list, null);
}
private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
// 循環(huán)遍歷sql語(yǔ)句配置
for (XNode context : list) {
final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
try {
// 解析配置節(jié)點(diǎn),并構(gòu)造產(chǎn)生SQL封裝體
statementParser.parseStatementNode();
} catch (IncompleteElementException e) {
configuration.addIncompleteStatement(statementParser);
}
}
}
SQL的處理,涉及到對(duì)配置信息的解析,以及對(duì)這些信息對(duì)封裝處理上
/**
* 該方法完成:
* 1、對(duì)sql配置中的數(shù)據(jù)進(jìn)行解析提取
* 2、通過(guò)builderAssistant的addMappedStatement方法來(lái)對(duì)解析到的數(shù)據(jù)進(jìn)行封裝,并保存到configuration中去
*/
public void parseStatementNode() {
// 下面對(duì)配置信息進(jìn)行逐個(gè)解析
String id = context.getStringAttribute("id");
String databaseId = context.getStringAttribute("databaseId");
if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
return;
}
Integer fetchSize = context.getIntAttribute("fetchSize");
Integer timeout = context.getIntAttribute("timeout");
String parameterMap = context.getStringAttribute("parameterMap");
String parameterType = context.getStringAttribute("parameterType");
Class<?> parameterTypeClass = resolveClass(parameterType);
String resultMap = context.getStringAttribute("resultMap");
String resultType = context.getStringAttribute("resultType");
String lang = context.getStringAttribute("lang");
LanguageDriver langDriver = getLanguageDriver(lang);
Class<?> resultTypeClass = resolveClass(resultType);
String resultSetType = context.getStringAttribute("resultSetType");
StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
String nodeName = context.getNode().getNodeName();
SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
boolean useCache = context.getBooleanAttribute("useCache", isSelect);
boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);
// Include Fragments before parsing
XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
includeParser.applyIncludes(context.getNode());
// Parse selectKey after includes and remove them.
processSelectKeyNodes(id, parameterTypeClass, langDriver);
// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
String resultSets = context.getStringAttribute("resultSets");
String keyProperty = context.getStringAttribute("keyProperty");
String keyColumn = context.getStringAttribute("keyColumn");
KeyGenerator keyGenerator;
String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
if (configuration.hasKeyGenerator(keyStatementId)) {
keyGenerator = configuration.getKeyGenerator(keyStatementId);
} else {
keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
? new Jdbc3KeyGenerator() : new NoKeyGenerator();
}
// 通過(guò)builderAssistant的addMappedStatement方法來(lái)對(duì)解析到的數(shù)據(jù)進(jìn)行封裝
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
public MappedStatement addMappedStatement(
String id,
SqlSource sqlSource,
StatementType statementType,
SqlCommandType sqlCommandType,
Integer fetchSize,
Integer timeout,
String parameterMap,
Class<?> parameterType,
String resultMap,
Class<?> resultType,
ResultSetType resultSetType,
boolean flushCache,
boolean useCache,
boolean resultOrdered,
KeyGenerator keyGenerator,
String keyProperty,
String keyColumn,
String databaseId,
LanguageDriver lang,
String resultSets) {
logger.info("解析mapper文件中的sql語(yǔ)句對(duì)象 元素 id:" + id);
if (unresolvedCacheRef) {
throw new IncompleteElementException("Cache-ref not yet resolved");
}
id = applyCurrentNamespace(id, false);
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
.resource(resource)
.fetchSize(fetchSize)
.timeout(timeout)
.statementType(statementType)
.keyGenerator(keyGenerator)
.keyProperty(keyProperty)
.keyColumn(keyColumn)
.databaseId(databaseId)
.lang(lang)
.resultOrdered(resultOrdered)
.resulSets(resultSets)
.resultMaps(getStatementResultMaps(resultMap, resultType, id))
.resultSetType(resultSetType)
.flushCacheRequired(valueOrDefault(flushCache, !isSelect))
.useCache(valueOrDefault(useCache, isSelect))
.cache(currentCache);
ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
if (statementParameterMap != null) {
statementBuilder.parameterMap(statementParameterMap);
}
// 存儲(chǔ)解析到到sql語(yǔ)句
MappedStatement statement = statementBuilder.build();
// 添加statement對(duì)象,對(duì)sql 的解析封裝完成
configuration.addMappedStatement(statement);
return statement;
}
到此,對(duì)sql的解析封裝完成,mybatis將mapper中的sql語(yǔ)句封裝到MappedStatement對(duì)象中,存儲(chǔ)到configuration對(duì)象的mappedStatements映射中。
Configuration類中的存儲(chǔ)SQL封裝的集合:
// 映射的SQL語(yǔ)句
protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection");
在執(zhí)行SQL 的時(shí)候還要從上述集合中獲取對(duì)應(yīng)的sql相關(guān)信息。
3.2 Mapper對(duì)象獲取
在前面的實(shí)例代碼中很容易就獲取到SqlSession對(duì)象了,有一行代碼是獲取Mapper對(duì)象的:
SysUserDao userDao = sqlSession.getMapper(SysUserDao.class);
先看SqlSession對(duì)象的獲取,通過(guò)上面分析,得到SqlSessionFactory的實(shí)現(xiàn)是DefaultSqlSessionFactory類。其openSession方法如下:
/**
* 創(chuàng)建SqlSession
* @see org.apache.ibatis.session.SqlSessionFactory#openSession()
*/
@Override
public SqlSession openSession() {
logger.info("open session...");
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
/**
* 獲取SqlSession對(duì)象
* @param execType
* @param level
* @param autoCommit
* @return
*/
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
logger.info("openSessionFromDataSource...");
// environment內(nèi)包含了數(shù)據(jù)源和事務(wù)相關(guān)的配置
final Environment environment = configuration.getEnvironment();
// 根據(jù)environment獲取事務(wù)管理
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
// 從environment中獲取DataSource
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
// 執(zhí)行器,通過(guò)Excutor來(lái)執(zhí)行SQL語(yǔ)句,Excutor是對(duì)Statement的封裝
final Executor executor = configuration.newExecutor(tx, execType);
// 創(chuàng)建了一個(gè)DefaultSqlSession對(duì)象,傳入了執(zhí)行器
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();
}
}
得到的SqlSession對(duì)象是DefaultSqlSession類的對(duì)象,現(xiàn)在看其getMapper方法
/**
* 直接去configuration中找相關(guān)的mapper對(duì)象
* @see org.apache.ibatis.session.SqlSession#getMapper(java.lang.Class)
*/
@Override
public <T> T getMapper(Class<T> type) {
logger.info("getMapper name:" + type.getName());
return configuration.<T>getMapper(type, this);
}
Configuration類中的getMapper方法:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
調(diào)用了MapperRegistry類中的方法,MapperRegistry主要負(fù)責(zé)mapper的注冊(cè),提供mapper代理功能。
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
// 讓代理去找mapper
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
// 關(guān)鍵: 創(chuàng)建,具體的mapper代理執(zhí)行類來(lái)創(chuàng)建。
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
public T newInstance(SqlSession sqlSession) {
// 注意MapperProxy代理類,后續(xù)mapper方法執(zhí)行的時(shí)候會(huì)到該代理的invoke方法中去
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
protected T newInstance(MapperProxy<T> mapperProxy) {
// 動(dòng)態(tài)代理我們寫的dao接口
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
mybatis通過(guò)jdk的動(dòng)態(tài)代理來(lái)為我們創(chuàng)建了mapper接口的實(shí)現(xiàn)。需要注意:
MapperProxy這個(gè)代理類,后續(xù)mapper方法執(zhí)行的時(shí)候會(huì)到該代理的invoke方法中去
3.3 Mapper方法執(zhí)行
/**
* MapperProxy在執(zhí)行時(shí)會(huì)觸發(fā)此方法
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 方法所在的是不是一個(gè)類? Mapper是一個(gè)接口,不是類,則跳過(guò)
System.out.println("method.getDeclaringClass():" + method.getDeclaringClass());
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
// 交給mapperMethod去執(zhí)行
return mapperMethod.execute(sqlSession, args);
}
MapperMethod是整個(gè)代理機(jī)制中的核心,對(duì)SqlSession中的方法做了封裝。
/**
* 根據(jù)sql類型去判斷執(zhí)行,最終還是去調(diào)用sqlSession中的方法去完成
* @param sqlSession
* @param args
* @return
*/
public Object execute(SqlSession sqlSession, Object[] args) {
// 返回結(jié)果
Object result;
// insert操作
if (SqlCommandType.INSERT == command.getType()) {
// 參數(shù)轉(zhuǎn)換處理
Object param = method.convertArgsToSqlCommandParam(args);
// 調(diào)用sqlSession的insert方法
result = rowCountResult(sqlSession.insert(command.getName(), param));
// update
} else if (SqlCommandType.UPDATE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
// delete
} else if (SqlCommandType.DELETE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
// select
} else if (SqlCommandType.SELECT == command.getType()) {
// 如果返回void,并且參數(shù)有結(jié)果處理器
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
// 返回多行結(jié)果的
} else if (method.returnsMany()) {
// 分析這兒
result = executeForMany(sqlSession, args);
// 返回類型是map
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else {
// 否則,就是查詢單個(gè)對(duì)象的
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
// flush操作
} else if (SqlCommandType.FLUSH == command.getType()) {
result = sqlSession.flushStatements();
} else {
// 不匹配,說(shuō)明,mapper中定義的方法不對(duì)
throw new BindingException("Unknown execution method for: " + command.getName());
}
//如果返回值為空 并且方法返回值類型是基礎(chǔ)類型 并且不是VOID 則拋出異常
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;
}
executeForMany方法:
/**
* 返回多行查詢結(jié)果的,主要是調(diào)用sqlSession的seleceList方法實(shí)現(xiàn)
* @param sqlSession
* @param args
* @param <E>
* @return
*/
private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
List<E> result;
Object param = method.convertArgsToSqlCommandParam(args);
// 如果參數(shù)中含有rowBounds則調(diào)用分頁(yè)查詢
if (method.hasRowBounds()) {
RowBounds rowBounds = method.extractRowBounds(args);
result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
} else {
// 沒(méi)有分頁(yè),普通查詢
result = sqlSession.<E>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;
}
對(duì)數(shù)據(jù)庫(kù)的操作 最終還是落到SqlSession(DefaultSqlSession實(shí)現(xiàn))類上了??床樵儾僮鳎?/p>
/**
* 在MapperProxy中調(diào)用
* @see org.apache.ibatis.session.SqlSession#selectList(java.lang.String, java.lang.Object, org.apache.ibatis.session.RowBounds)
*/
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
// 實(shí)際上是然executor去執(zhí)行了。
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();
}
}
DefaultSqlSession中的selectList 方法
/**
* 在MapperProxy中調(diào)用
* @see org.apache.ibatis.session.SqlSession#selectList(java.lang.String, java.lang.Object, org.apache.ibatis.session.RowBounds)
*/
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
// 實(shí)際上是然executor去執(zhí)行了。
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();
}
}
BaseExecutor中query方法:
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameter);
// 生成緩存key
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
SimpleExecutor中的查詢方法:
/**
* 在SqlSession中調(diào)用
* @see org.apache.ibatis.executor.BaseExecutor#doQuery(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.session.ResultHandler, org.apache.ibatis.mapping.BoundSql)
*/
@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();
// 構(gòu)建StatementHandler對(duì)象
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
// 預(yù)編譯和基礎(chǔ)設(shè)置
stmt = prepareStatement(handler, ms.getStatementLog());
// StatementHandler封裝了Statement,讓其處理,并通過(guò)resultHandler來(lái)完成對(duì)結(jié)果集對(duì)回調(diào)處理
return handler.<E>query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
最終通過(guò)結(jié)果處理器進(jìn)行回調(diào),完成對(duì)查詢到的結(jié)果集進(jìn)行處理并返回。
4、總結(jié)
整體上,按照查詢涉及到的代碼過(guò)了一遍,對(duì)mybatis的源碼有了個(gè)大體的了解,后續(xù)對(duì)其逐步進(jìn)行解析。