1.Mybatis执行增删改的底层核心接口是Executor.update,如果我们想对它进行拦截处理,则需要拦截此方法
2.Mybatis执行查询的底层核心接口是ResultSetHandler.handleResultSets,如果我们想对它进行拦截处理,则需要拦截此方法
定义增删改的拦截器:
@Intercepts({
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
})
@Slf4j
public class IbatisUpdateInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
if (invocation.getTarget() instanceof Executor && invocation.getArgs().length == 2) {
return invokeUpdate(invocation);
}
} finally {
// 回滚到原生对象
MybatisContextHolder.rollback();
}
return invocation.proceed();
}
private Object invokeUpdate(Invocation invocation) throws Exception {
Executor executor = (Executor) invocation.getTarget();
// 获取第一个参数
MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
// 非insert/update,不处理
if (ms.getSqlCommandType() != SqlCommandType.INSERT && ms.getSqlCommandType() != SqlCommandType.UPDATE) {
return invocation.proceed();
}
Object paramObj = invocation.getArgs()[1];
// 无参数不处理
if (paramObj == null) {
return invocation.proceed();
}
if (!needEncryptDecrypt(paramObj) && !isBatchUpdate(paramObj)) {
return invocation.proceed();
}
// 加密
if (paramObj instanceof Map) {
Map map =