Mybatis 插件
Mybatis插件主要是通過JDK動態代理實作的,插件可以針對介面中的方法進行代理增強,在Mybatis中比較重要的介面如下:
Executor:sql執行器,包含多個實作類,比如SimpleExecutorStatementHander:sql陳述句處理器,用于將sql陳述句與Statement的映射,實作類有:PrepareStatementHandler、SimpleStatementHandler、CallBackStatementHandlerParameterHandler:用于引數處理,將傳入的引數一一的決議并將型別決議出來,會用到TypeHandler,最終這些資料會用于StatementHandler進行資料的映射,比如?對應的值的映射ResultSetHandler:結果值的處理器,用于資料在查詢出來之后,將資料通過ResultSet把資料映射給回傳值型別的類上,通過反射(內省)處理映射資料

Mybatis插件的使用
Mybatis插件使用通過@Intercepts注解進行介面的系結,如下定義一個插件類
/**
* @author <a href="https://www.cnblogs.com/redwinter/archive/2022/08/20/[email protected]">redwinter</a>
* @since 1.0
**/
@Intercepts({@Signature(
type = StatementHandler.class,
method = "prepare",
args = {Connection.class, Integer.class}
)})
@Slf4j
public class MyPlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
log.info("對方法進行增強....");
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
log.info("獲取屬性值:{}", properties);
}
}
然后需要將定義的插件配置mybatis的組態檔中:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 參考db.properties組態檔 -->
<properties resource="db.properties"/>
<!--在 MyBatis 組態檔 mybatis-config.xml 里面添加一項 setting 來選擇其它日志實作,
可選的值有:SLF4J、LOG4J、LOG4J2、JDK_LOGGING、COMMONS_LOGGING、STDOUT_LOGGING、NO_LOGGING,
或者是實作了 org.apache.ibatis.logging.Log 介面,且構造方法以字串為引數的類完全限定名,-->
<settings>
<!-- 列印sql日志 -->
<setting name="logImpl" value="https://www.cnblogs.com/redwinter/archive/2022/08/20/STDOUT_LOGGING" />
<!--開啟二級快取-->
<setting name="cacheEnabled" value="https://www.cnblogs.com/redwinter/archive/2022/08/20/true"/>
</settings>
<typeAliases>
<package name="com.redwinter.study.mybatis.model"/>
</typeAliases>
<!--mybatis插件的配置 -->
<plugins>
<plugin interceptor="mybatis.plugins.MyPlugin">
<property name="redwinter" value="https://www.cnblogs.com/redwinter/archive/2022/08/20/冬玲"/>
</plugin>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--不能配置方言,配置后分頁失效-->
<!-- <property name="dialect" value="https://www.cnblogs.com/redwinter/archive/2022/08/20/com.github.pagehelper.dialect.rowbounds.MySqlRowBoundsDialect"/>-->
</plugin>
</plugins>
<!--
development : 開發模式
work : 作業模式
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置資料庫連接資訊 -->
<dataSource type="POOLED">
<!-- value屬性值參考db.properties組態檔中配置的值 -->
<property name="driver" value="https://www.cnblogs.com/redwinter/archive/2022/08/20/${driver}" />
<property name="url" value="https://www.cnblogs.com/redwinter/archive/2022/08/20/${url}" />
<property name="username" value="https://www.cnblogs.com/redwinter/archive/2022/08/20/${name}" />
<property name="password" value="https://www.cnblogs.com/redwinter/archive/2022/08/20/${password}" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- <mapper resource="mappers/UserMapper.xml"/>-->
<package name="mybatis.mapper"/>
</mappers>
</configuration>
這樣就可以生效了,當我們執行資料查詢的時候,只要是執行了StatementHandler#prepare方法,那么都會執行到自定的邏輯增強
日志如下:
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1386958]
16:02:38.260 [main] INFO mybatis.plugins.MyPlugin - 對方法進行增強....
==> Preparing: update user set name = ?, age = ? where id = ?
==> Parameters: 李四(String), 19(Integer), 1(Integer)
<== Updates: 1
Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1386958]
Cache Hit Ratio [mybatis.mapper.UserMapper]: 0.5
16:02:38.303 [main] INFO mybatis.plugins.MyPlugin - 對方法進行增強....
==> Preparing: select * from user where id = ?
==> Parameters: 1(Integer)
<== Columns: id, age, name
<== Row: 1, 19, 李四
<== Total: 1
false
原始碼分析
首先我們自定義的插件,需要配置到xml檔案中,然后在啟動程式的時候,會先創建SqlSession,那么在之前需要進行xml的決議,在Mybatis中決議時通過SqlSessionFactoryBuilder創建一個SqlSessionFactory,然后在通過SqlSessionFactory創建一個SqlSession,在這個程序中,SqlSesssionFactoryBuilder會去創建一個XmlConfigBuilder去決議Xml配置,在XmlConfigBuilder的建構式中會創建Configuration類,這個類中保存了Mybatis的所有配置,
然后XmlConfigBuilder呼叫parse方法開始決議配置,決議時會根據xml中的配置一一決議,并且決議是有順序的以來,決議的順序是:
properties用于配置外部資源的屬性配置,比如配置jdbc的組態檔用于下面的環境資訊配置settings用于設定Mybatis內置的設定,比如日志、快取等,這些配置其實都是Configuration類中的setter方法的配置,Mybatis使用反射(內省)將Configuration的屬性通過Properties物件key-value一一進行了對應,typeAliases用于配置別名的配置,在Mybatis中默認了很多的別名,比如Java的基本資料型別,常用了的集合物件,日期物件等都進行了提前的別名配置,這些配置都會注冊到TypeAliasRegistry的一個Map中,plugins用于插件的配置,比如自定義的插件,Mybatis的插件是通過JDK動態代理進行增強操作的,Mybatis提供了Interceptor介面,最侄訓將這些介面全部加載Interceptor加入到InterceptorChain中的List集合中,objectFactory、objectWrapperFactory、reflectorFactory這些不怎么常用enviroments用于配置環境資訊的,比如JDBC資料源的資訊,這個配置可以配置多個環境,比如開發環境,生產環境等databaseIdProvider這個也不常用typeHandlers型別處理器的配置mappers用于配置Mapper.xml的配置或者Mapper介面的配置,可以配置包路徑,xml的路徑資源

SqlSessionFactoryBuilder#build方法:
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
// 創建一個決議xml的構建器,建構式中會創建一個Configuration類
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
// 決議xml配置
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
創建XMLConfiBuilder類
private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
super(new Configuration());
ErrorContext.instance().resource("SQL Mapper Configuration");
this.configuration.setVariables(props);
this.parsed = false;
this.environment = environment;
this.parser = parser;
}
創建Configuration類
public Configuration() {
// 添加別名
typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class);
typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class);
typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class);
typeAliasRegistry.registerAlias("PERPETUAL", PerpetualCache.class);
typeAliasRegistry.registerAlias("FIFO", FifoCache.class);
typeAliasRegistry.registerAlias("LRU", LruCache.class);
typeAliasRegistry.registerAlias("SOFT", SoftCache.class);
typeAliasRegistry.registerAlias("WEAK", WeakCache.class);
typeAliasRegistry.registerAlias("DB_VENDOR", VendorDatabaseIdProvider.class);
typeAliasRegistry.registerAlias("XML", XMLLanguageDriver.class);
typeAliasRegistry.registerAlias("RAW", RawLanguageDriver.class);
typeAliasRegistry.registerAlias("SLF4J", Slf4jImpl.class);
typeAliasRegistry.registerAlias("COMMONS_LOGGING", JakartaCommonsLoggingImpl.class);
typeAliasRegistry.registerAlias("LOG4J", Log4jImpl.class);
typeAliasRegistry.registerAlias("LOG4J2", Log4j2Impl.class);
typeAliasRegistry.registerAlias("JDK_LOGGING", Jdk14LoggingImpl.class);
typeAliasRegistry.registerAlias("STDOUT_LOGGING", StdOutImpl.class);
typeAliasRegistry.registerAlias("NO_LOGGING", NoLoggingImpl.class);
typeAliasRegistry.registerAlias("CGLIB", CglibProxyFactory.class);
typeAliasRegistry.registerAlias("JAVASSIST", JavassistProxyFactory.class);
languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class);
languageRegistry.register(RawLanguageDriver.class);
}
創建TypeAliasRegistry類
private final Map<String, Class<?>> typeAliases = new HashMap<>();
public TypeAliasRegistry() {
// 注冊別名,最終全部會注冊到Map中
registerAlias("string", String.class);
registerAlias("byte", Byte.class);
registerAlias("char", Character.class);
registerAlias("character", Character.class);
registerAlias("long", Long.class);
registerAlias("short", Short.class);
registerAlias("int", Integer.class);
registerAlias("integer", Integer.class);
registerAlias("double", Double.class);
registerAlias("float", Float.class);
registerAlias("boolean", Boolean.class);
registerAlias("byte[]", Byte[].class);
registerAlias("char[]", Character[].class);
registerAlias("character[]", Character[].class);
registerAlias("long[]", Long[].class);
registerAlias("short[]", Short[].class);
registerAlias("int[]", Integer[].class);
registerAlias("integer[]", Integer[].class);
registerAlias("double[]", Double[].class);
registerAlias("float[]", Float[].class);
registerAlias("boolean[]", Boolean[].class);
registerAlias("_byte", byte.class);
registerAlias("_char", char.class);
registerAlias("_character", char.class);
registerAlias("_long", long.class);
registerAlias("_short", short.class);
registerAlias("_int", int.class);
registerAlias("_integer", int.class);
registerAlias("_double", double.class);
registerAlias("_float", float.class);
registerAlias("_boolean", boolean.class);
registerAlias("_byte[]", byte[].class);
registerAlias("_char[]", char[].class);
registerAlias("_character[]", char[].class);
registerAlias("_long[]", long[].class);
registerAlias("_short[]", short[].class);
registerAlias("_int[]", int[].class);
registerAlias("_integer[]", int[].class);
registerAlias("_double[]", double[].class);
registerAlias("_float[]", float[].class);
registerAlias("_boolean[]", boolean[].class);
registerAlias("date", Date.class);
registerAlias("decimal", BigDecimal.class);
registerAlias("bigdecimal", BigDecimal.class);
registerAlias("biginteger", BigInteger.class);
registerAlias("object", Object.class);
registerAlias("date[]", Date[].class);
registerAlias("decimal[]", BigDecimal[].class);
registerAlias("bigdecimal[]", BigDecimal[].class);
registerAlias("biginteger[]", BigInteger[].class);
registerAlias("object[]", Object[].class);
registerAlias("map", Map.class);
registerAlias("hashmap", HashMap.class);
registerAlias("list", List.class);
registerAlias("arraylist", ArrayList.class);
registerAlias("collection", Collection.class);
registerAlias("iterator", Iterator.class);
registerAlias("ResultSet", ResultSet.class);
}
呼叫XMLConfigBuilder#parse方法
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
// 決議配置,從根的configuration的標簽開始
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);
// 加載自定義的日志列印
loadCustomLogImpl(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"));
// 決議mappers標簽
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
決議插件標簽:
private void pluginElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
String interceptor = child.getStringAttribute("interceptor");
Properties properties = child.getChildrenAsProperties();
Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor().newInstance();
interceptorInstance.setProperties(properties);
// 將插件全部加入到配置中,最侄訓加載到InterceptorChain類的List集合中
configuration.addInterceptor(interceptorInstance);
}
}
}
當我們呼叫方法執行Sql的時候,Mybatis會通過SqlSession去委派呼叫Executor的介面的方法進行執行,比如我們呼叫selectList(statementId) 去執行查詢,那么會呼叫:
private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
// 獲取Mapper中決議的配置,這個類中存放了sql陳述句,回傳型別,引數型別等
MappedStatement ms = configuration.getMappedStatement(statement);
return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
呼叫query方法就會委派到Executor介面的實作類BaseExecutor類中進行執行:
@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
// 獲取sql陳述句,決議出sql陳述句,引數型別,引數值等資料
BoundSql boundSql = ms.getBoundSql(parameter);
// 創建一個快取key,用于快取存盤使用
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
呼叫query多載方法:如果快取中有,那么就從快取中獲取,如果沒有那么執行資料庫查詢
@SuppressWarnings("unchecked")
@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 {
queryStack++;
// 從快取中獲取資料
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
// 查詢資料從資料庫
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;
}
最侄訓中到SimpleExecutor實作類的doQuery方法去真正執行查詢:
@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
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
在呼叫newStatementHandler方法是會執行到插件的pluginAll方法,執行動態代理的創建代理物件:
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;
}
攔截器鏈去呼叫pluginAll,然后呼叫Interceptor的plugin方法創建代理物件:
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
// 遍歷所有的插件,然后執行plugin方法,獲取到代理的物件
target = interceptor.plugin(target);
}
return target;
}
// Interceptor的默認介面方法plugin
default Object plugin(Object target) {
return Plugin.wrap(target, this);
}
// Plugin類中的包裝創建一個代理物件
public static Object wrap(Object target, Interceptor interceptor) {
// 獲取類和方法集合
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
// 目標的介面,代理生成的介面
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
// 創建一個jdk動態代理
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
這樣的話就完成了攔截器插件的代理物件的創建,這里創建出來的代理物件就是StatementHandler,在前面自定義的插件,配置的是攔截StatementHandler#prepare方法,那么在哪里執行的呢?
回到Executor介面實作類SimpleExecutor了中doQuery方法,這個方法中會去創建一個預編譯SQL處理器,執行prepareStatement方法:
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
// 獲取一個資料庫連接
Connection connection = getConnection(statementLog);
// 獲取Statement 這里可能獲取到PrepareStatement 、SimpleStatement、CallbackStatement
stmt = handler.prepare(connection, transaction.getTimeout());
// 設定引數
handler.parameterize(stmt);
return stmt;
}
這里的話就會呼叫prepare方法,這個方法就是自定義插件配置需要攔截的方法,由于這個handler是一個代理物件,我們都知道只要是代理物件,只要執行代理物件的任何方法都會去執行InvoketionHandler介面的invoke方法,當執行到這個方法的時候就會呼叫到我們自定義的插件類中intercept方法:
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
if (methods != null && methods.contains(method)) {
// 如果攔截的方法與執行的方法一致那么執行intercept方法進行增加強
return interceptor.intercept(new Invocation(target, method, args));
}
// 如果不是則執行方法即可
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
所以只要我們執行了sql查詢,那么都會通過JDK動態代理創建的代理物件去執行到這個增強方法,
插件的擴展
在Mybatis中有個分頁的插件叫PageHelper,這個插件就是使用了Mybatis插件機制完成的,當然還有比如早期的TkMapper插件,接下來分析一下PageHelper是如何實作分頁機制的,
引入依賴:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.0</version>
</dependency>
然后在mybatis-config.xml組態檔中配置插件讓分頁插件生效:
<plugins>
<plugin interceptor="mybatis.plugins.MyPlugin">
<property name="redwinter" value="https://www.cnblogs.com/redwinter/archive/2022/08/20/冬玲"/>
</plugin>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--不能配置方言,配置后分頁失效-->
<!-- <property name="dialect" value="https://www.cnblogs.com/redwinter/archive/2022/08/20/com.github.pagehelper.dialect.rowbounds.MySqlRowBoundsDialect"/>-->
</plugin>
</plugins>
然后就可以直接使用了:
@Test
public void testPageHelper() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 設定分頁引數
PageHelper.startPage(1, 2);
List<User> users = mapper.selectAll();
// 構建分頁資訊
PageInfo<User> pageInfo = new PageInfo<User>(users);
System.out.println(pageInfo);
}
日志如下:
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@14a2528]
11:06:43.511 [main] INFO mybatis.plugins.MyPlugin - 對方法進行增強....
==> Preparing: SELECT count(0) FROM user
==> Parameters:
<== Columns: count(0)
<== Row: 3
<== Total: 1
Cache Hit Ratio [mybatis.mapper.UserMapper]: 0.0
11:06:43.562 [main] INFO mybatis.plugins.MyPlugin - 對方法進行增強....
==> Preparing: select * from user LIMIT ?
==> Parameters: 2(Integer)
<== Columns: id, age, name
<== Row: 1, 19, 李四
<== Row: 2, null, 里斯
<== Total: 2
PageInfo{pageNum=1, pageSize=2, size=2, startRow=1, endRow=2, total=3, pages=2, list=Page{count=true, pageNum=1, pageSize=2, startRow=0, endRow=2, total=3, pages=2, reasonable=false, pageSizeZero=false}[User(id=1, age=19, name=李四), User(id=2, age=0, name=里斯)], prePage=0, nextPage=2, isFirstPage=true, isLastPage=false, hasPreviousPage=false, hasNextPage=true, navigatePages=8, navigateFirstPage=1, navigateLastPage=2, navigatepageNums=[1, 2]}
可以看到這里執行了兩條sql陳述句,一個是查詢總條數,一個是分頁查詢,那PageHelper怎么實作的呢?
PageHelper 分頁原始碼決議
由于我們在mybatis-config.xml中配置了分頁插件,那么直接進PageInterceptor這個類去看看,找到intercept方法:
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
RowBounds rowBounds = (RowBounds) args[2];
ResultHandler resultHandler = (ResultHandler) args[3];
Executor executor = (Executor) invocation.getTarget();
CacheKey cacheKey;
BoundSql boundSql;
//由于邏輯關系,只會進入一次
if (args.length == 4) {
//4 個引數時
boundSql = ms.getBoundSql(parameter);
cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
} else {
//6 個引數時
cacheKey = (CacheKey) args[4];
boundSql = (BoundSql) args[5];
}
checkDialectExists();
//對 boundSql 的攔截處理
if (dialect instanceof BoundSqlInterceptor.Chain) {
boundSql = ((BoundSqlInterceptor.Chain) dialect).doBoundSql(BoundSqlInterceptor.Type.ORIGINAL, boundSql, cacheKey);
}
List resultList;
//呼叫方法判斷是否需要進行分頁,如果不需要,直接回傳結果
if (!dialect.skip(ms, parameter, rowBounds)) {
//判斷是否需要進行 count 查詢
if (dialect.beforeCount(ms, parameter, rowBounds)) {
//查詢總數
Long count = count(executor, ms, parameter, rowBounds, null, boundSql);
//處理查詢總數,回傳 true 時繼續分頁查詢,false 時直接回傳
if (!dialect.afterCount(count, parameter, rowBounds)) {
//當查詢總數為 0 時,直接回傳空的結果
return dialect.afterPage(new ArrayList(), parameter, rowBounds);
}
}
resultList = ExecutorUtil.pageQuery(dialect, executor,
ms, parameter, rowBounds, resultHandler, boundSql, cacheKey);
} else {
//rowBounds用引數值,不使用分頁插件處理時,仍然支持默認的記憶體分頁
resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}
return dialect.afterPage(resultList, parameter, rowBounds);
} finally {
if(dialect != null){
dialect.afterAll();
}
}
}
根據Debug發現這回傳的物件實際上是一個Page物件,這個物件繼承ArrayList,所以在查詢多個資料時可以直接通過List集合獲取,最終在分裝到PageInfo物件中就完成了分頁資料的封裝,那么這些分頁資料是何時設定進去的呢?
實際上在進行PageHelper.startPage(1, 2);時,這個引數設定在ThreadLocal中,在PageMethod類中:
/**
* 開始分頁
*
* @param pageNum 頁碼
* @param pageSize 每頁顯示數量
* @param count 是否進行count查詢
* @param reasonable 分頁合理化,null時用默認配置
* @param pageSizeZero true且pageSize=0時回傳全部結果,false時分頁,null時用默認配置
*/
public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {
Page<E> page = new Page<E>(pageNum, pageSize, count);
page.setReasonable(reasonable);
page.setPageSizeZero(pageSizeZero);
//當已經執行過orderBy的時候
Page<E> oldPage = getLocalPage();
if (oldPage != null && oldPage.isOrderByOnly()) {
page.setOrderBy(oldPage.getOrderBy());
}
setLocalPage(page);
return page;
}
呼叫setLocalPage方法就會設定到ThreadLocal中:
protected static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>();
protected static boolean DEFAULT_COUNT = true;
/**
* 設定 Page 引數
*
* @param page
*/
protected static void setLocalPage(Page page) {
LOCAL_PAGE.set(page);
}
在執行查詢的到時候會呼叫到getLocalPage方法獲取ThreadLocal中的引數,然后設定到分頁引數中并構建出sql陳述句用于分頁查詢,在執行完之后會在finally中呼叫clearPage清除掉ThreadLoacl中的資料,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/502384.html
標籤:其他
下一篇:字典(dict)
