Springboot的Mybatis拦截器实现[通俗易懂]

2022-10-29 13:31:35 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,其实就是拦截器功能

MyBatis 允许拦截的接口

MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:

  1. Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  2. ParameterHandler (getParameterObject, setParameters)
  3. ResultSetHandler (handleResultSets, handleOutputParameters)
  4. StatementHandler (prepare, parameterize, batch, update, query)

Executor接口的部分方法,比如update,query,commit,rollback等方法,还有其他接口的一些方法等。

总体概括为:

  1. 拦截执行器的方法
  2. 拦截参数的处理
  3. 拦截结果集的处理,为sql执行之后的结果拦截过滤
  4. 拦截Sql语法构建的处理,为sql执行之前的拦截进行sql封装

MyBatis拦截器的接口定义

一共有三个方法interceptpluginsetProperties

setProperties()

方法主要是用来从配置中获取属性。

如果是使用xml式配置拦截器,可在Mybatis配置文件中添加如下节点,属性可以以如下方式传递

代码语言:javascript复制
<plugins>
	<plugin interceptor="tk.mybatis.simple.plugin.XXXInterceptor">
		<property name="propl" value="valuel" />
		<property name="prop2" value="value2" />
	</plugin>
</plugins>

如果在Spring boot中使用,则需要单独写一个配置类,如下:

代码语言:javascript复制
@Configuration
public class MybatisInterceptorConfig { 
   
    @Bean
    public String myInterceptor(SqlSessionFactory sqlSessionFactory) { 
   
        ExecutorInterceptor executorInterceptor = new ExecutorInterceptor();
        Properties properties = new Properties();
        properties.setProperty("prop1","value1");
        executorInterceptor.setProperties(properties);
        return "interceptor";
    }
}

如果说不需要配置属性,则在spring boot中,不需要去编写配置类,只需要像我一样在拦截器上加个@Component即可。

plugin()

方法用于指定哪些方法可以被此拦截器拦截。

intercept()

方法是用来对拦截的sql进行具体的操作。

注解实现

MyBatis拦截器用到了两个注解:@Intercepts@Signature

代码语言:javascript复制
@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}),
        }
)

type的值与类名相同,method方法名相同,为了避免方法重载,args中指定了各个参数的类型和个数,可通过invocation.getArgs()获取参数数组。

Executor 拦截器实现

代码语言:javascript复制
@Intercepts({ 

@Signature(
type= Executor.class,
method = "query",
args = { 
MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)
})
@Slf4j
@Component
public class ExecutorInterceptor implements Interceptor { 

@Override
public Object intercept(Invocation invocation) throws Throwable { 

String sql = ExecutorPluginUtils.getSqlByInvocation(invocation);
//可以对sql重写
log.error("拦截器ExecutorInterceptor:" sql);
//sql = "SELECT id from BUS_RECEIVER where id = ? ";
ExecutorPluginUtils.resetSql2Invocation( invocation,  sql);
return invocation.proceed();
}
@Override
public Object plugin(Object o) { 

return Plugin.wrap(o, this);
}
@Override
public void setProperties(Properties properties) { 

}
}

ParameterHandler 拦截器实现

代码语言:javascript复制
/** * @Author: ynz * @Date: 2018/12/23/023 12:07 */
@Intercepts({ 

@Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class),
})
@Component
@Slf4j
public class ParamInterceptor  implements Interceptor { 

@Override
public Object intercept(Invocation invocation) throws Throwable { 

log.error("拦截器ParamInterceptor");
//拦截 ParameterHandler 的 setParameters 方法 动态设置参数
if (invocation.getTarget() instanceof ParameterHandler) { 

ParameterHandler parameterHandler = (ParameterHandler) invocation.getTarget();
PreparedStatement ps = (PreparedStatement) invocation.getArgs()[0];
// 反射获取 BoundSql 对象,此对象包含生成的sql和sql的参数map映射
Field boundSqlField = parameterHandler.getClass().getDeclaredField("boundSql");
boundSqlField.setAccessible(true);
BoundSql boundSql = (BoundSql) boundSqlField.get(parameterHandler);
// 反射获取 参数对像
Field parameterField = 
parameterHandler.getClass().getDeclaredField("parameterObject");
parameterField.setAccessible(true);
Object parameterObject = parameterField.get(parameterHandler);
if (parameterObject instanceof Map) { 

//将参数中的name值改为2
((Map) parameterObject).put("name","2");
}
// 改写的参数设置到原parameterHandler对象
parameterField.set(parameterHandler, parameterObject);
parameterHandler.setParameters(ps);
log.error(JSON.toJSONString(boundSql.getParameterMappings()));
log.error(JSON.toJSONString(parameterObject));
}
return invocation.proceed();
}
@Override
public Object plugin(Object o) { 

return Plugin.wrap(o, this);
}
@Override
public void setProperties(Properties properties) { 

}
}

ResultSetHandler 拦截器实现

代码语言:javascript复制
@Intercepts({ 

@Signature(type = ResultSetHandler.class, method = "handleResultSets", args={ 
Statement.class})
})
@Component
@Slf4j
public class ResultInterceptor implements Interceptor { 

@Override
public Object intercept(Invocation invocation) throws Throwable { 

log.error("拦截器ResultInterceptor");
// ResultSetHandler resultSetHandler1 = (ResultSetHandler) invocation.getTarget();
//通过java反射获得mappedStatement属性值
//可以获得mybatis里的resultype
Object result = invocation.proceed();
if (result instanceof ArrayList) { 

ArrayList resultList = (ArrayList) result;
for (int i = 0; i < resultList.size(); i  ) { 

Object oi = resultList.get(i);
Class c = oi.getClass();
Class[] types = { 
String.class};
Method method = c.getMethod("setAddress", types);
// 调用obj对象的 method 方法
method.invoke(oi, "china");
}
}
return result;
}
@Override
public Object plugin(Object target) { 

return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) { 

}
}

StatementHandler 拦截器实现

代码语言:javascript复制
/** * @Author: ynz * @Date: 2018/12/23/023 14:22 */
@Intercepts(
{ 
@Signature(
type = StatementHandler.class,
method = "prepare",
args = { 
Connection.class, Integer.class}
)
})
@Component
@Slf4j
public class StatementInterceptor implements Interceptor { 

@Override
public Object intercept(Invocation invocation) throws Throwable { 

StatementHandler statementHandler = 
(StatementHandler) PluginUtils.realTarget(invocation.getTarget());
MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
MappedStatement mappedStatement = 
(MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
//只拦截select方法
if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) { 

return invocation.proceed();
}
BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
//获取到sql
String originalSql = boundSql.getSql();
//可以对originalSql进行改写
log.error("拦截器StatementInterceptor:" originalSql);
metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
Object parameterObject = boundSql.getParameterObject();
return invocation.proceed();
}
@Override
public Object plugin(Object target) { 

return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) { 

}
}

Spring Boot整合

方法1:手写一个配置类

代码语言:javascript复制
@Configuration
public class MybatisInterceptorConfig { 

@Bean
public String myInterceptor(SqlSessionFactory sqlSessionFactory) { 

ExecutorInterceptor executorInterceptor = new ExecutorInterceptor();
Properties properties = new Properties();
properties.setProperty("prop1","value1");
executorInterceptor.setProperties(properties);
sqlSessionFactory.getConfiguration().addInterceptor(executorInterceptor);
sqlSessionFactory.getConfiguration().addInterceptor(new ParamInterceptor());
sqlSessionFactory.getConfiguration().addInterceptor(new ResultInterceptor());
return "interceptor";
}
}

方法2:在拦截器上加@Component注解

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/195748.html原文链接:https://javaforall.cn

0 人点赞