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

二、獲得sqlSession對(duì)象源碼分析
/**
* 通過(guò)sqlSessionFactory.openSession進(jìn)行獲取sqlSession對(duì)象
* 源碼位置:org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSession()
*/
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
/**
* 通過(guò)數(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);
// 獲取一個(gè)事務(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 {
// 簡(jiǎn)單的sql執(zhí)行器
executor = new SimpleExecutor(this, transaction);
}
// 判斷Mybatis的全局配置文件是否開(kāi)啟二級(jí)緩存
if (cacheEnabled) {
// 開(kāi)啟緩存,吧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);
// 長(zhǎng)度為1,拿第一個(gè)
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) {
// 長(zhǎng)度大于一,拋異常
throw new TooManyResultsException(
"Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
// 沒(méi)有拿到返回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 {
// 通過(guò)statement去全局配置文件中獲取MappedStatement(得到mapper中增刪改查的節(jié)點(diǎn))
MappedStatement ms = configuration.getMappedStatement(statement);
// 通過(guò)執(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 {
// 通過(guò)參數(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是否開(kāi)啟了緩存 <cache></cache>
Cache cache = ms.getCache();
// 有緩存
if (cache != null) {
// 判斷是否需要刷新緩存
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, boundSql);
@SuppressWarnings("unchecked")
// 去二級(jí)緩存中獲?。ㄑb飾者模式)
List<E> list = (List<E>) tcm.getObject(cache, key);
// 二級(jí)緩存沒(méi)有找到
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);
}
/**
* 一級(jí)緩存查詢的調(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 {
// 從一級(jí)緩存中獲取數(shù)據(jù)
queryStack++;
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {
// 緩存里面有,進(jìn)行處理
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
// 緩存沒(méi)有,進(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ù)庫(kù)中查詢
* 源碼位置: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ù)庫(kù)查詢
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
localCache.removeObject(key);
}
// 一級(jí)緩存進(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 {
// 得到整體的配置對(duì)象
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í)行查詢語(yǔ)句
* 源碼位置: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語(yǔ)句解析執(zhí)行的過(guò)程及原理的文章就介紹到這了,更多相關(guān)SQL語(yǔ)句解析原理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mysql數(shù)據(jù)庫(kù)查詢基礎(chǔ)命令詳解
這篇文章主要介紹了mysql數(shù)據(jù)庫(kù)查詢基礎(chǔ)命令,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-11-11
解決Navicat導(dǎo)入數(shù)據(jù)庫(kù)數(shù)據(jù)結(jié)構(gòu)sql報(bào)錯(cuò)datetime(0)的問(wèn)題
這篇文章主要介紹了解決Navicat導(dǎo)入數(shù)據(jù)庫(kù)數(shù)據(jù)結(jié)構(gòu)sql報(bào)錯(cuò)datetime(0)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
MYSQL設(shè)置觸發(fā)器權(quán)限問(wèn)題的解決方法
這篇文章主要介紹了MYSQL設(shè)置觸發(fā)器權(quán)限問(wèn)題的解決方法,需要的朋友可以參考下2014-09-09
解決MySQL報(bào)錯(cuò)Error 3948 (42000): Loading loc
在執(zhí)行MySQL項(xiàng)目過(guò)程中意外出現(xiàn)的報(bào)錯(cuò),之前也沒(méi)有遇到過(guò),報(bào)錯(cuò)信息如下,Error 3948 (42000): Loading local data is disabled; this must be enabled on both the client an,本文小編就給大家介紹一下解決報(bào)錯(cuò)的方法,需要的朋友可以參考下2023-09-09

