SQL語句解析執(zhí)行的過程及原理
一、sqlSession簡單介紹
- 拿到
SqlSessionFactory對象后,會調(diào)用SqlSessionFactory的openSesison方法,這個方法會創(chuàng)建一個Sql執(zhí)行器(Executor),這個Sql執(zhí)行器會代理你配置的攔截器方法。 - 獲得上面的Sql執(zhí)行器后,會創(chuàng)建一個
SqlSession(默認(rèn)使用DefaultSqlSession),這個SqlSession中也包含了Configration對象,所以通過SqlSession也能拿到全局配置; - 獲得
SqlSession對象后就能執(zhí)行各種CRUD方法了。

二、獲得sqlSession對象源碼分析
/**
* 通過sqlSessionFactory.openSession進(jìn)行獲取sqlSession對象
* 源碼位置:org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSession()
*/
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
/**
* 通過數(shù)據(jù)源去獲取SqlSession
* 源碼位置:org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSessionFromDataSource(ExecutorType, TransactionIsolationLevel, boolean)
*/
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level,
boolean autoCommit) {
Transaction tx = null;
try {
// 獲取環(huán)境變量
final Environment environment = configuration.getEnvironment();
// 獲取事務(wù)工廠
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
// 獲取一個事務(wù)
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
// 獲取執(zhí)行器,這邊獲得的執(zhí)行器已經(jīng)代理攔截器的功能
final Executor executor = configuration.newExecutor(tx, execType);
// 根據(jù)獲取的執(zhí)行器創(chuàng)建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();
}
}
/**
* 獲取執(zhí)行器
* 源碼位置:org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSessionFromDataSource(ExecutorType, TransactionIsolationLevel, boolean)
*/
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
// 默認(rèn)使用SIMPLE的執(zhí)行器
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
// 批量的執(zhí)行器
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
// 可重復(fù)使用的執(zhí)行器
executor = new ReuseExecutor(this, transaction);
} else {
// 簡單的sql執(zhí)行器
executor = new SimpleExecutor(this, transaction);
}
// 判斷Mybatis的全局配置文件是否開啟二級緩存
if (cacheEnabled) {
// 開啟緩存,吧executor包裝為CachingExecutor
executor = new CachingExecutor(executor);
}
// 插件的調(diào)用:責(zé)任鏈模式
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
三、SQL執(zhí)行流程,以查詢?yōu)槔?/h2>

/**
* 查詢的入口方法
* 源碼位置:org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(String, Object)
*/
public <T> T selectOne(String statement, Object parameter) {
// Popular vote was to return null on 0 results and throw exception on too many.
// 查詢數(shù)據(jù)
List<T> list = this.<T>selectList(statement, parameter);
// 長度為1,拿第一個
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) {
// 長度大于一,拋異常
throw new TooManyResultsException(
"Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
// 沒有拿到返回null
return null;
}
}
/**
* 查詢數(shù)據(jù)
* 源碼位置:org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(String, Object, RowBounds)
*/
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
// 通過statement去全局配置文件中獲取MappedStatement(得到mapper中增刪改查的節(jié)點(diǎn))
MappedStatement ms = configuration.getMappedStatement(statement);
// 通過執(zhí)行器去執(zhí)行SQL
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();
}
}
/**
* 執(zhí)行查詢操作的準(zhǔn)備工作
* 源碼位置:org.apache.ibatis.executor.CachingExecutor.query(MappedStatement, Object, RowBounds, ResultHandler)
*/
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds,
ResultHandler resultHandler) throws SQLException {
// 通過參數(shù)進(jìn)行sql解析
BoundSql boundSql = ms.getBoundSql(parameterObject);
CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
/**
* 執(zhí)行查詢操作的準(zhǔn)備工作
* 源碼位置:org.apache.ibatis.executor.CachingExecutor.query(MappedStatement, Object, RowBounds, ResultHandler, CacheKey, BoundSql)
*/
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds,
ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
// 判斷sql是否開啟了緩存 <cache></cache>
Cache cache = ms.getCache();
// 有緩存
if (cache != null) {
// 判斷是否需要刷新緩存
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, boundSql);
@SuppressWarnings("unchecked")
// 去二級緩存中獲?。ㄑb飾者模式)
List<E> list = (List<E>) tcm.getObject(cache, key);
// 二級緩存沒有找到
if (list == null) {
// 查詢數(shù)據(jù),并放入緩存
list = delegate.<E>query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
tcm.putObject(cache, key, list); // issue #578 and #116
}
return list;
}
}
// 查詢數(shù)據(jù)
return delegate.<E>query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
/**
* 一級緩存查詢的調(diào)用
* 源碼位置:org.apache.ibatis.executor.BaseExecutor.query(MappedStatement, Object, RowBounds, ResultHandler, CacheKey, BoundSql)
*/
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());
// 已經(jīng)關(guān)閉了,拋異常
if (closed) {
throw new ExecutorException("Executor was closed.");
}
// 清空本地緩存
if (queryStack == 0 && ms.isFlushCacheRequired()) {
clearLocalCache();
}
List<E> list;
try {
// 從一級緩存中獲取數(shù)據(jù)
queryStack++;
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {
// 緩存里面有,進(jìn)行處理
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
// 緩存沒有,進(jìn)行查詢
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
} finally {
queryStack--;
}
if (queryStack == 0) {
for (DeferredLoad deferredLoad : deferredLoads) {
deferredLoad.load();
}
// issue #601
deferredLoads.clear();
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
// issue #482
clearLocalCache();
}
}
return list;
}
/**
* 在數(shù)據(jù)庫中查詢
* 源碼位置:org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(MappedStatement, Object, RowBounds, ResultHandler, CacheKey, BoundSql)
*/
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds,
ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
// 去數(shù)據(jù)庫查詢
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
localCache.removeObject(key);
}
// 一級緩存進(jìn)行緩存
localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
/**
* 查詢邏輯
* 源碼位置:org.apache.ibatis.executor.SimpleExecutor.doQuery(MappedStatement, Object, RowBounds, ResultHandler, BoundSql)
*/
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();
// 內(nèi)部封裝了ParameterHandler和ResultSetHandler
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds,
resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
// 執(zhí)行查詢
return handler.<E>query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
/**
* 執(zhí)行查詢語句
* 源碼位置:org.apache.ibatis.executor.statement.SimpleStatementHandler.query(Statement, ResultHandler)
*/
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
// 得到要執(zhí)行的sql
String sql = boundSql.getSql();
// 執(zhí)行sql
statement.execute(sql);
// 處理結(jié)果集
return resultSetHandler.<E>handleResultSets(statement);
}到此這篇關(guān)于SQL語句解析執(zhí)行的過程及原理的文章就介紹到這了,更多相關(guān)SQL語句解析原理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MySQL數(shù)據(jù)權(quán)限的實(shí)現(xiàn)詳情
這篇文章主要介紹了MySQL數(shù)據(jù)權(quán)限的實(shí)現(xiàn)詳情,文章通過實(shí)際案例,從代碼實(shí)戰(zhàn)的角度來實(shí)現(xiàn)這樣的一個數(shù)據(jù)權(quán)限。具體詳細(xì)介紹,具有一定的參考價值2022-08-08
服務(wù)器上的mysql實(shí)現(xiàn)讀取sql文件
這篇文章主要介紹了服務(wù)器上的mysql實(shí)現(xiàn)讀取sql文件方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
MySQL查詢表中重復(fù)數(shù)據(jù)的實(shí)現(xiàn)
在數(shù)據(jù)庫中,我們經(jīng)常需要查詢重復(fù)字段來確保數(shù)據(jù)的準(zhǔn)確性,如果數(shù)據(jù)中有重復(fù)字段,則可能會導(dǎo)致查詢結(jié)果錯誤,本文就想詳細(xì)的介紹了MySQL查詢表中重復(fù)數(shù)據(jù),感興趣的可以了解一下2023-08-08
MySQL百萬級數(shù)據(jù)大分頁查詢優(yōu)化的實(shí)現(xiàn)
在數(shù)據(jù)庫開發(fā)過程中我們經(jīng)常會使用分頁,但是如果是百萬級數(shù)據(jù)呢,本文就詳細(xì)的介紹一下MySQL百萬級數(shù)據(jù)大分頁查詢優(yōu)化的實(shí)現(xiàn),感興趣的可以了解一下2022-01-01
MySQL中實(shí)現(xiàn)動態(tài)表單中JSON元素精準(zhǔn)匹配的方法示例
本文主要介紹了MySQL中實(shí)現(xiàn)動態(tài)表單中JSON元素精準(zhǔn)匹配的方法示例,重點(diǎn)講解如何在將設(shè)計(jì)好的動態(tài)表單信息進(jìn)行提取,具有一定的參考價值,感興趣的可以了解一下2024-07-07
mysql通過my.cnf修改默認(rèn)字符集為utf-8的方法和注意事項(xiàng)
本文主要給大家介紹mysql通過my.cnf修改默認(rèn)字符集為utf-8的方法,當(dāng)然你也可以設(shè)置成別的,國際點(diǎn)還是utf-8好,以及在修改過程中要注意的一些事項(xiàng),有需要的朋友們可以參考借鑒。2016-09-09

