aop切面记录mybatis的SQL语句
前言
在我们使用mybatis作为的开发的时候,有时候我们需要拿到运行的SQL语句,这个在开发阶段是比较方便拿到的,直接在mapper.xml文件里抠出来就是了,但是上了生产环境,我们如果想定点的知道一些方法的SQL语句的话,就比较麻烦,可能需要根据参数,来看xml代码,从而生成SQL。可能有的小伙伴会说,直接把mybatis的打印SQL的功能打开就行了。但是在生产环境,我们往往是不开启这个配置的,因为一个请求过来,查询的语句太多了,输出出来的日志信息很多,而日志多了,往往会让我们错过一些重要的信息,也不利于排查问题。所以这里我就在尽量不变原有的代码的前提下,使用自定义注解的方式,只需要在mapper上,打上注解标签,就可以自动在控制台打印SQL语句。
开工
定义一个自定义注解
/**
* 描述:获取mybatis执行的SQL语句的注解
* @author:hl.yuan
* @date:2021-03-29
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ModelSubmit {
String value() default "";
}
- @Target 是表示在用个那个上面,ElementType.METHOD 是用在方法上面
- @Retention 注解的生命周期,表示注解会被保留到什么阶段,可以选择编译阶段、类加载阶段,或运行阶段
- @Documented 注解信息会被添加到Java文档中
创建一个自定义注解后,我们需要创建一个aop的切面类,来定义切面点,这里实现的原理,其实用的是spring的动态代理的功能。
package com.hanlin.backend.common.aspect;
import com.hanlin.backend.common.util.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* 描述:
*
* @author:hl.yuan
* @date:2021-03-29
*/
@Component
@Aspect
@Slf4j
public class MyAdvice {
@Autowired
private SqlSessionFactory sqlSessionFactory;
/**
* 定义切点
*/
@Pointcut("@annotation(com.hanlin.backend.common.annotation.ModelSubmit)")
private void pc() {
}
/**
* 指定该方法是前置通知,并指定切入点
*/
@Before("MyAdvice.pc()")
public void before() {
}
/**
* 后置通知
*/
@AfterReturning("MyAdvice.pc()")
public void afterReturning() {
}
/**
* 环绕通知
*
* @param pjp
* @return
* @throws Throwable
*/
@Around("MyAdvice.pc()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
// 1.从redis中获取主数据库,若获取不到直接退出,否则判断当前数据源是会否为主,若不为主,则切换到主数据源
// 2.调用目标方法
Object proceed = pjp.proceed();
// 3.获取SQL
String sql = SqlUtils.getMybatisSql(pjp, sqlSessionFactory);
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
String namespace = method.getDeclaringClass().getName();
String methodName = method.getName();
// 4.打印SQL语句
log.info("【SQL语句打印 {}.{}】: {}}", namespace, methodName, sql);
// 5.通知同步程序
return proceed;
}
/**
* 异常通知
*/
@AfterThrowing("MyAdvice.pc()")
public void afterException() {
}
/**
* 后置通知
*/
@After("MyAdvice.pc()")
public void after() {
}
}
代码解读:这里其实在aop的环绕通知里进行操作的,我们把SqlSessionFactory对象拿到了,然后在SqlUtils工具类里根据SqlSessionFactory拿到当前的执行的SQL语句,并打印出来。
接下来我们在看下SqlUtils工具类代码:
package com.hanlin.backend.common.util;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.util.*;
/**
* 描述:
*
* @author:hl.yuan
* @date:2021-03-29
*/
public class SqlUtils {
/**
* 获取aop中的SQL语句
*
* @param pjp
* @param sqlSessionFactory
* @return
* @throws IllegalAccessException
*/
public static String getMybatisSql(ProceedingJoinPoint pjp, SqlSessionFactory sqlSessionFactory) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>(16);
//1.获取namespace+methdoName
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
String namespace = method.getDeclaringClass().getName();
String methodName = method.getName();
//2.根据namespace+methdoName获取相对应的MappedStatement
Configuration configuration = sqlSessionFactory.getConfiguration();
MappedStatement mappedStatement = configuration.getMappedStatement(namespace + "." + methodName);
// //3.获取方法参数列表名
// Parameter[] parameters = method.getParameters();
//4.形参和实参的映射
Object[] objects = pjp.getArgs(); //获取实参
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameterAnnotations.length; i++) {
Object object = objects[i];
if (parameterAnnotations[i].length == 0) { //说明该参数没有注解,此时该参数可能是实体类,也可能是Map,也可能只是单参数
if (object.getClass().getClassLoader() == null && object instanceof Map) {
map.putAll((Map<? extends String, ?>) object);
System.out.println("该对象为Map");
} else {//形参为自定义实体类
map.putAll(objectToMap(object));
System.out.println("该对象为用户自定义的对象");
}
} else {//说明该参数有注解,且必须为@Param
for (Annotation annotation : parameterAnnotations[i]) {
if (annotation instanceof Param) {
map.put(((Param) annotation).value(), object);
}
}
}
}
//5.获取boundSql
BoundSql boundSql = mappedStatement.getBoundSql(map);
return showSql(configuration, boundSql);
}
/**
* 解析BoundSql,生成不含占位符的SQL语句
*
* @param configuration
* @param boundSql
* @return
*/
private static String showSql(Configuration configuration, BoundSql boundSql) {
Object parameterObject = boundSql.getParameterObject();
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
if (parameterMappings.size() > 0 && parameterObject != null) {
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = parameterMapping.getProperty();
String[] s = metaObject.getObjectWrapper().getGetterNames();
s.toString();
if (metaObject.hasGetter(propertyName)) {
Object obj = metaObject.getValue(propertyName);
sql = sql.replaceFirst("\\?", getParameterValue(obj));
} else if (boundSql.hasAdditionalParameter(propertyName)) {
Object obj = boundSql.getAdditionalParameter(propertyName);
sql = sql.replaceFirst("\\?", getParameterValue(obj));
}
}
}
}
return sql;
}
/**
* 若为字符串或者日期类型,则在参数两边添加''
*
* @param obj
* @return
*/
private static String getParameterValue(Object obj) {
String value = null;
if (obj instanceof String) {
value = "'" + obj.toString() + "'";
} else if (obj instanceof Date) {
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
value = "'" + formatter.format(new Date()) + "'";
} else {
if (obj != null) {
value = obj.toString();
} else {
value = "";
}
}
return value;
}
/**
* 获取利用反射获取类里面的值和名称
*
* @param obj
* @return
* @throws IllegalAccessException
*/
private static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Class<?> clazz = obj.getClass();
System.out.println(clazz);
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj);
map.put(fieldName, value);
}
return map;
}
}
注意:这里的我们自定义的注解,只能使用在mapper的方法上面。如图
最后测试的效果:
参考的博客地址:https://blog.csdn.net/chengtanyong4777/article/details/100178668