說明
之前使用了com.github.pagehelper.pagehelper
實現(xiàn)分頁锻梳,現(xiàn)在參考源代碼,自己簡單實現(xiàn)一下功能邦鲫。
插件源碼地址:https://github.com/pagehelper/Mybatis-PageHelper
基礎(chǔ)代碼
基礎(chǔ)代碼可以參考:《SpringBoot項目實戰(zhàn)(001)mybatis通過xml實現(xiàn)mapper》
主要代碼說明
-
DataSourceConfig
:數(shù)據(jù)源配置,可以配置mybatis的攔截器 -
PageInfo
古今;用于傳入分頁參數(shù) -
Dialect
滔以;方言,針對不同數(shù)據(jù)庫抵碟,實現(xiàn)不同的方言坏匪,本文使用mysql -
MybatisInterceptor
适滓;mybatis攔截器,實現(xiàn)分頁功能
第一步罚屋,安裝攔截器
首先把攔截器創(chuàng)建出來嗅绸,并在mybatis的config中,使用攔截器猛拴。
簡單修改DataSourceConfig.java
// mybatis配置
private org.apache.ibatis.session.Configuration createMybatisConfig() {
......
// 加入攔截器
config.addInterceptor(getMybatisIntercepts());
return config;
}
private Interceptor getMybatisIntercepts() {
Interceptor interceptor = new MybatisInterceptor();
return interceptor;
}
MybatisInterceptor.java
代碼瞧柔,基本上是空的
package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
/**
* MybatisInterceptor
*/
@Intercepts({
@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class }),
@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class, CacheKey.class, BoundSql.class }), })
public class MybatisInterceptor implements Interceptor {
private volatile IDialect dialect;
public Object intercept(Invocation invocation) throws Throwable {
try {
Object[] args = invocation.getArgs();
return null;
} finally {
if (dialect != null) {
dialect.afterAll();
}
}
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
}
IDialect.java
package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.RowBounds;
public interface IDialect {
void afterAll();
String getPagedSql(BoundSql boundSql,RowBounds rowBounds);
}
斷點打在MybatisInterceptor
的intercept
方法處,運行debug哥蔚,postman調(diào)個GET方法蛛蒙,可得:
可以看到,有四個參數(shù)深夯,仔細看一下,大致功能:
- mybatis的mapper方面的信息
- 參數(shù)方面的信息
- 分頁信息:limit offset
- null
那我們需要做的就是找到查詢語句雹拄,根據(jù)dialect
改寫為分頁的語句掌呜,返回結(jié)果即可滓玖。
第二步质蕉,調(diào)整功能
整理參數(shù)模暗,把三個參數(shù)包括Executor都整理出來。我們的目的是通過調(diào)整sql語句绷蹲,再使用Executor完成原本的調(diào)用顾孽。
// 參數(shù)
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
RowBounds rowBounds = (RowBounds) args[2];
ResultHandler resultHandler = (ResultHandler) args[3];
// 執(zhí)行器
Executor executor = (Executor) invocation.getTarget();
// sql
BoundSql boundSql = ms.getBoundSql(parameter);
// 分頁sql
String sql = dialect.getPagedSql(boundSql, rb);
新增MySqlDialect若厚,實現(xiàn)功能getPageSql
,將BoundSql
中的sql調(diào)整為分頁的疤估。
//實現(xiàn)
package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;
public class MySqlDialect implements IDialect {
@Override
public void afterAll() {
}
@Override
public String getPagedSql(BoundSql boundSql, RowBounds rowBounds) {
String sql = boundSql.getSql();
StringBuilder sb = new StringBuilder();
sb.append(sql);
sb.append(" LIMIT ");
sb.append(rowBounds.getOffset());
sb.append(",");
sb.append(rowBounds.getLimit());
return sb.toString();
}
}
第三步霎冯,輸入?yún)?shù)
現(xiàn)在修改整條request鏈路沈撞,所有findall
方法增加pageinfo參數(shù)。
首先缠俺,新增pageinfo
類型:
package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;
import lombok.Data;
@Data
public class PageInfo {
// 分頁壹士,第幾頁
private int pageNum;
// 分頁,每頁大小
private int pageSize;
}
OrderController 修改 orders 方法唯笙,增加一個參數(shù)
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<OrderBean> orders(OrderCondition orderCondition,PageInfo pageinfo) {
return orderService.findAll(orderCondition,pageinfo);
}
IBaseService 修改findall方法,增加pageinfo參數(shù)七嫌,注意@Param("pageinfo")
定義參數(shù)的名字
default List<Bean> findAll(@Param("conditionQC") Condition condition,@Param("pageinfo") PageInfo
pageinfo){
return getBaseDao().findAll(condition,pageinfo);
}
IBaseDao 修改findall方法抄瑟,增加pageinfo參數(shù)枉疼,注意@Param("pageinfo")
定義參數(shù)的名字
public List<Bean> findAll(@Param("conditionQC") Condition conditionQC,@Param("pageinfo") PageInfo pageinfo);
第四步,完善攔截器
在攔截器中找到pageinfo參數(shù)惹资,如果有分頁參數(shù)航闺,就將值傳給方言進行分頁,最后返回數(shù)據(jù)侮措。
方言可以通過datasource的配置乖杠,自動讀取,本文直接設(shè)置為MysqlDialect畏吓。
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();
BoundSql boundSql = ms.getBoundSql(parameter);
ParamMap params = (ParamMap) parameter;
// 判斷參數(shù)中是否有分頁
if (params.containsKey("pageinfo")) {
PageInfo pageinfo = (PageInfo) params.get("pageinfo");
if (pageinfo.getPageNum() > 0 && pageinfo.getPageSize() > 0) {
RowBounds rb = new RowBounds((pageinfo.getPageNum() - 1) * pageinfo.getPageSize(),
pageinfo.getPageSize());
// 使用方言分頁
String sql = dialect.getPagedSql(boundSql, rb);
boundSql = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), parameter);
return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, null, boundSql);
}
}
return invocation.proceed();
} finally {
if (dialect != null) {
dialect.afterAll();
}
}
}
使用postman測試
list方法菲饼,使用分頁參數(shù)列赎,返回分頁結(jié)果:
list方法,不使用分頁參數(shù),返回所有結(jié)果:
findOne方法(后臺不接受分頁參數(shù)),可以看到加入分頁參數(shù)褂乍,也不會分頁: