1.前言
首先要理解MyBatis的運(yùn)行原理海渊,首先第一個(gè)需要掌握的是代理模式尔崔。因?yàn)橹暗囊恍┪恼吕锩妫覀儗懙陌咐喊椋锩娑加猩昝鱠ao層的接口勃痴。我們只是定義了一系列接口定義,而并沒有實(shí)現(xiàn)其邏輯接口热康。而這些都是MyBatis使用了代理模式幫我們實(shí)現(xiàn)了沛申。
補(bǔ)充下:了解代理模式看我之前的一篇關(guān)于代理模式的博文
2.構(gòu)建SqlSessionFactory過程
SqlSessionFactory是MyBatis的核心,主要提供SqlSession姐军。而SqlSessionFactory是采用生成器模式又稱構(gòu)建者模式生成铁材。
public static SqlSessionFactory buildSqlSessionFactory() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("config/mybatis-config.xml");
return new SqlSessionFactoryBuilder().build(inputStream);
}
2.1SqlSessionFactory構(gòu)建步驟
1.使用org.apache.ibatis.builder.xml.XMLConfigBuilder去解析配置xml屬性,并將解析的內(nèi)容存放在org.apache.ibatis.session.Configuration中
2.使用Configuration對象去創(chuàng)建SqlSessionFactory奕锌。因?yàn)镾qlSessionFactory是接口著觉,所以MyBatis內(nèi)置了默認(rèn)的SqlSessionFactory實(shí)現(xiàn)類DefaultSqlSessionFactory
使用建造者模式的好處就是將生成SqlSessionFactory的過程與xml解析的過程分割開來,這樣便于代碼維護(hù)惊暴。
2.2構(gòu)建Configuration
org.apache.ibatis.builder.xml.XMLConfigBuilder重要的兩個(gè)方法
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
3.SqlSession運(yùn)行過程
SqlSession是獲取Mapper的重要接口饼丘。
因?yàn)樯厦娅@取的是DefaultSqlSessionFactory,所以使用到的是DefaultSqlSession
3.1 Mapper映射器使用動態(tài)代理
package org.apache.ibatis.binding.MapperProxyFactory
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
MapperProxy實(shí)現(xiàn)java.lang.reflect.InvocationHandler
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
4.SqlSession的重要對象
- 1.Executor(執(zhí)行器對象)
由它來調(diào)度StatementHandler缴守、ParameterHandler葬毫、ResultHandler等來執(zhí)行對應(yīng)的SQL
- 2.StatementHandler(數(shù)據(jù)庫會話器)
它的作用是使用數(shù)據(jù)庫的Statement(PreparedStatemnet)執(zhí)行操作镇辉,它是四大對象的核心屡穗,起到承上啟下的作用贴捡。
- 3.ParameterHandler(參數(shù)處理器)
用于SQL對參數(shù)的處理
- 4.ResultHandler(結(jié)果處理器)
是進(jìn)行最后數(shù)據(jù)集(ResultSet)的封裝返回
4.1Executor
Executor是我們在創(chuàng)建好SqlSessionFactory之后,使用factory.openSession()進(jìn)行創(chuàng)建村砂。在MyBatis存在三種執(zhí)行器烂斋。
1.simple。簡易執(zhí)行器础废,不配置就是默認(rèn)的執(zhí)行器
2.resuse汛骂。是一種執(zhí)行器重用預(yù)處理語句
3.batch。執(zhí)行器重用語句和批量更新评腺,它是針對批量專用的執(zhí)行器
- openSession
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
上面獲取的getDefaultExecutorType是protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;如果沒有設(shè)置執(zhí)行器的類型的話是simple
- openSessionFromDataSource
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
final Executor executor = configuration.newExecutor(tx, execType);
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();
}
}
- newExecutor
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
- SimpleExecutor內(nèi)部實(shí)現(xiàn)
@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 handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.<E>query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection, transaction.getTimeout());
handler.parameterize(stmt);
return stmt;
}
MyBatis根據(jù)Configuration來構(gòu)建StatementHandler帘瞭,然后使用prepareStatement,對SQL編譯并對參數(shù)進(jìn)行初始化蒿讥。
實(shí)現(xiàn)過程:
- 1.調(diào)用StatementHandler的prepare進(jìn)行預(yù)編譯和基礎(chǔ)設(shè)置
- 2.調(diào)用StatementHandler的parameterize來設(shè)置參數(shù)并執(zhí)行
- 3.利用ResultSetHandler組裝查詢結(jié)果給調(diào)用者完成一次查詢
4.2StatementHandler(數(shù)據(jù)庫會話器)
數(shù)據(jù)庫會話器是專門處理數(shù)據(jù)庫會話的
- 創(chuàng)建StatementHandler實(shí)例
在包中org.apache.ibatis.session.Configuration
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
RoutingStatementHandler并不是一個(gè)真實(shí)的服務(wù)對象蝶念,其代碼只是做一個(gè)簡單工廠的職責(zé),使用方式不太好芋绸。
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
switch (ms.getStatementType()) {
case STATEMENT:
delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
case PREPARED:
delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
case CALLABLE:
delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
default:
throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
}
}
- 常用的PreparedStatementHandler
PreparedStatementHandler是繼承BaseStatementHandler
@Override
public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException {
ErrorContext.instance().sql(boundSql.getSql());
Statement statement = null;
try {
statement = instantiateStatement(connection);
setStatementTimeout(statement, transactionTimeout);
setFetchSize(statement);
return statement;
} catch (SQLException e) {
closeStatement(statement);
throw e;
} catch (Exception e) {
closeStatement(statement);
throw new ExecutorException("Error preparing statement. Cause: " + e, e);
}
}
@Override
protected Statement instantiateStatement(Connection connection) throws SQLException {
String sql = boundSql.getSql();
if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) {
String[] keyColumnNames = mappedStatement.getKeyColumns();
if (keyColumnNames == null) {
return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
} else {
return connection.prepareStatement(sql, keyColumnNames);
}
} else if (mappedStatement.getResultSetType() != null) {
return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY);
} else {
return connection.prepareStatement(sql);
}
}
4.3 ParameterHandler
設(shè)置SQL參數(shù)媒殉。handler.parameterize(stmt);
public void parameterize(Statement statement) throws SQLException {
parameterHandler.setParameters((PreparedStatement) statement);
}
- 設(shè)置參數(shù)是使用的DefaultParameterHandler
@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;
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 = configuration.newMetaObject(parameterObject);
value = metaObject.getValue(propertyName);
}
TypeHandler typeHandler = parameterMapping.getTypeHandler();
JdbcType jdbcType = parameterMapping.getJdbcType();
if (value == null && jdbcType == null) {
jdbcType = configuration.getJdbcTypeForNull();
}
try {
typeHandler.setParameter(ps, i + 1, value, jdbcType);
} catch (TypeException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
} catch (SQLException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
}
}
}
}
}
4.4ResultSetHandler
用于組裝數(shù)據(jù)返回的結(jié)果集到對應(yīng)的POJO上
public interface ResultSetHandler {
<E> List<E> handleResultSets(Statement stmt) throws SQLException;
<E> Cursor<E> handleCursorResultSets(Statement stmt) throws SQLException;
void handleOutputParameters(CallableStatement cs) throws SQLException;
}
宏觀的看,MyBatis的整理架構(gòu)圖如下: