前言
相信大家對攔截器并不陌生,對mybatis也不陌生,
有用過pagehelper的,那么對mybatis攔截器也不陌生了,按照使用的規則觸發sql攔截,幫我們自動添加分頁引數 ,
那么今天,我們的實踐 自定義mybatis攔截器也是如此, 本篇文章實踐的效果:
針對一些使用 單個物體類去接識訓傳結果的 mapper方法,我們攔截檢測,如果沒寫 LIMIT 1 ,我們將自動幫忙填充,達到查找單條資料 效率優化的效果,
ps: 當然,跟著該篇學會了這個之后,那么可以擴展的東西就多了,大家按照自己的想法或是專案需求都可以自己發揮, 我該篇的實踐僅僅作為拋磚引玉吧,
正文
實踐的準備 :
整合mybatis ,然后故意寫了3個查詢方法, 1個是list 串列資料,2個是 單條資料 ,

我們通過自己寫一個MybatisInterceptor實作 mybatis框架的 Interceptor來做文章:
MybatisInterceptor.java :
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.*;
/**
* @Author JCccc
* @Description
* @Date 2021/12/14 16:56
*/
@Component
@Intercepts({
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MybatisInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
//獲取執行引數
Object[] objects = invocation.getArgs();
MappedStatement ms = (MappedStatement) objects[0];
//決議執行sql的map方法,開始自定義規則匹配邏輯
String mapperMethodAllName = ms.getId();
int lastIndex = mapperMethodAllName.lastIndexOf(".");
String mapperClassStr = mapperMethodAllName.substring(0, lastIndex);
String mapperClassMethodStr = mapperMethodAllName.substring((lastIndex + 1));
Class<?> mapperClass = Class.forName(mapperClassStr);
Method[] methods = mapperClass.getMethods();
Class<?> returnType;
for (Method method : methods) {
if (method.getName().equals(mapperClassMethodStr)) {
returnType = method.getReturnType();
if (returnType.isAssignableFrom(List.class)) {
System.out.println("回傳型別是 List");
System.out.println("針對List 做一些操作");
} else if (returnType.isAssignableFrom(Set.class)) {
System.out.println("回傳型別是 Set");
System.out.println("針對Set 做一些操作");
} else{
BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
String oldSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ");
if (!oldSql.contains("LIMIT")){
String newSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ") + " LIMIT 1";
BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
boundSql.getParameterMappings(), boundSql.getParameterObject());
MappedStatement newMs = newMappedStatement(ms, new MyBoundSqlSqlSource(newBoundSql));
for (ParameterMapping mapping : boundSql.getParameterMappings()) {
String prop = mapping.getProperty();
if (boundSql.hasAdditionalParameter(prop)) {
newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
}
}
Object[] queryArgs = invocation.getArgs();
queryArgs[0] = newMs;
System.out.println("列印新SQL陳述句" + newSql);
}
}
}
}
//繼續執行邏輯
return invocation.proceed();
}
@Override
public Object plugin(Object o) {
//獲取代理權
if (o instanceof Executor) {
//如果是Executor(執行增刪改查操作),則攔截下來
return Plugin.wrap(o, this);
} else {
return o;
}
}
/**
* 定義一個內部輔助類,作用是包裝 SQL
*/
class MyBoundSqlSqlSource implements SqlSource {
private BoundSql boundSql;
public MyBoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
@Override
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
MappedStatement.Builder builder = new
MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
builder.keyProperty(ms.getKeyProperties()[0]);
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.resultSetType(ms.getResultSetType());
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
}
@Override
public void setProperties(Properties properties) {
//讀取mybatis組態檔中屬性
}
}
簡單代碼端決議:
① 拿出執行引數,里面有很多東西給我們用的,我本篇主要是用MappedStatement,大家可以發揮自己的想法, 打debug可以自己看看里面的東西,
//獲取執行引數 Object[] objects = invocation.getArgs(); MappedStatement ms = (MappedStatement) objects[0];


② 這里我主要是使用了從MappedStatement里面拿出來的id,做切割分別切出來 目前執行的sql的mapper是哪個,然后方法是哪個,
String mapperMethodAllName = ms.getId();
int lastIndex = mapperMethodAllName.lastIndexOf(".");
String mapperClassStr = mapperMethodAllName.substring(0, lastIndex);
String mapperClassMethodStr = mapperMethodAllName.substring((lastIndex + 1));
③ 這就是我自己隨便寫的一下,我直接根據切割出來的mapper類找出里面的方法,主要是為了拿出每個方法的回傳型別,因為 我這篇實踐內容就是,判斷出單個pojo接受的mapper方法,加個LIMIT 1 , 其他的 LIST 、SET 、 Page 等等這些,我暫時不做擴展,
Class<?> mapperClass = Class.forName(mapperClassStr); Method[] methods = mapperClass.getMethods(); Class<?> returnType;
④這一段代碼就是該篇的拓展邏輯了,從MappedStatement里面拿出 SqlSource,然后再拿出BoundSql,然后一頓操作 給加上 LIMIT 1 , 然后new 一個新的 MappedStatement,一頓操作塞回去invocation 里面,
BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
String oldSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ");
if (!oldSql.contains("LIMIT")){
String newSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ") + " LIMIT 1";
BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
boundSql.getParameterMappings(), boundSql.getParameterObject());
MappedStatement newMs = newMappedStatement(ms, new MyBoundSqlSqlSource(newBoundSql));
for (ParameterMapping mapping : boundSql.getParameterMappings()) {
String prop = mapping.getProperty();
if (boundSql.hasAdditionalParameter(prop)) {
newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
}
}
Object[] queryArgs = invocation.getArgs();
queryArgs[0] = newMs;
System.out.println("列印新SQL陳述句:" + newSql);
}
OK,最后簡單來試試效果 :


最后再重申一下,本篇文章內容只是一個拋磚引玉,隨便想的一些實踐效果,大家可以按照自己的想法發揮,
最后再補充一個 解決 mybatis自定義攔截器和 pagehelper 攔截器 沖突導致失效的問題出現的 解決方案:
加上一個攔截器配置類
MyDataSourceInterceptorConfig.java :
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @Author JCccc
* @Description
* @Date 2021/12/14 16:56
*/
@Component
public class MyDataSourceInterceptorConfig implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private MybatisInterceptor mybatisInterceptor;
@Autowired
private List<SqlSessionFactory> sqlSessionFactories;
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
for (SqlSessionFactory factory : sqlSessionFactories) {
factory.getConfiguration().addInterceptor(mybatisInterceptor);
}
}
}
最后最后再補充多一些,
文中 針對攔截的是Executor 這種介面的插件,
其實 還可以使用ParameterHandler、ResultSetHandler、StatementHandler,
每當執行這四種介面物件的方法時,就會進入攔截方法,然后我們可以根據不同的插件去拿不同的引數,
類似:
@Signature(method = "prepare", type = StatementHandler.class, args = {Connection.class,Integer.class})
然后可以做個轉換,也是可以取出相關的 BoundSql 等等 :
if (!(invocation.getTarget() instanceof RoutingStatementHandler)){
return invocation.proceed();
}
RoutingStatementHandler statementHandler = (RoutingStatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql().toUpperCase();
ParameterHandler、ResultSetHandler、StatementHandler、Executor ,不同的插件攔截,有不同的使用場景,想深入的看客們,可以深一下,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/400539.html
標籤:java
