自定義注解
/**
* 獲取sql注解
*
* @author ruoyi
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SqlLogs
{
/**
* 是否打印sql
*/
public boolean hasSqlLog() default false;
}
自定義攔截器
@Slf4j
@AllArgsConstructor
//@Aspect
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
@Component
public class SqlLogsInterceptor extends AbstractSqlParserHandler implements Interceptor {
private DataSource dataSource;
@Override
public Object intercept(Invocation invocation) throws Throwable {
Map<String,Object> sqlMap = new HashMap<>();
Boolean hasSqlLogs = false;
StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
this.sqlParser(metaObject);
// 先判斷是不是SELECT操作 不是直接過(guò)濾
MappedStatement mappedStatement =
(MappedStatement) metaObject.getValue("delegate.mappedStatement");
if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
return invocation.proceed();
}
final Object[] args = invocation.getArgs();
//獲取執(zhí)行方法的位置
String namespace = mappedStatement.getId();
//獲取mapper名稱
String className = namespace.substring(0,namespace.lastIndexOf("."));
//獲取方法名
String methedName= namespace.substring(namespace.lastIndexOf(".") + 1,namespace.length());
//獲取當(dāng)前mapper 的方法
Method[] ms = Class.forName(className).getMethods();
for(Method m : ms){
if(m.getName().equals(methedName)){
//獲取注解 來(lái)判斷是不是要儲(chǔ)存sql
SqlLogs annotation = m.getAnnotation(SqlLogs.class);
if(annotation != null){
hasSqlLogs = annotation.hasSqlLog();
}
}
}
//如果是有注解值為true,便獲取sql處理參數(shù)
if(hasSqlLogs){
BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
// 執(zhí)行的SQL語(yǔ)句
String originalSql = boundSql.getSql();
// SQL語(yǔ)句的參數(shù)
Object parameterObject = boundSql.getParameterObject();
if(parameterObject != null){
originalSql = showSql(configuration, boundSql);
}
System.err.println("sql :"+originalSql);
}
return invocation.proceed();
}
/**
* 生成攔截對(duì)象的代理
*
* @param target 目標(biāo)對(duì)象
* @return 代理對(duì)象
*/
@Override
public Object plugin(Object target) {
if (target instanceof StatementHandler) {
return Plugin.wrap(target, this);
}
return target;
}
/**
* 獲取參數(shù)值
* @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 = "to_date('" + formatter.format(obj) + "','yyyy-MM-dd hh24:mi:ss')";
} else {
if (obj != null) {
value = obj.toString();
} else {
value = "";
}
}
System.err.println("獲取值: "+value);
return value;
}
/***
* sql 參數(shù)替換
* @param configuration
* @param boundSql
* @return
*/
public static String showSql(Configuration configuration, BoundSql boundSql) {
//獲取參數(shù)對(duì)象
Object parameterObject = boundSql.getParameterObject();
//獲取當(dāng)前的sql語(yǔ)句有綁定的所有parameterMapping屬性
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
//去除空格
String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
if (parameterMappings.size() > 0 && parameterObject != null) {
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
/* 如果參數(shù)滿足:org.apache.ibatis.type.TypeHandlerRegistry#hasTypeHandler(java.lang.Class<?>)
org.apache.ibatis.type.TypeHandlerRegistry#TYPE_HANDLER_MAP
* 即是不是屬于注冊(cè)類型(TYPE_HANDLER_MAP...等/有沒(méi)有相應(yīng)的類型處理器)
* */
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
} else {
//裝飾器煤蹭,可直接操作屬性值 ---》 以parameterObject創(chuàng)建裝飾器
//MetaObject 是 Mybatis 反射工具類祠丝,通過(guò) MetaObject 獲取和設(shè)置對(duì)象的屬性值
MetaObject metaObject = configuration.newMetaObject(parameterObject);
//循環(huán) parameterMappings 所有屬性
for (ParameterMapping parameterMapping : parameterMappings) {
//獲取property屬性
String propertyName = parameterMapping.getProperty();
System.err.println("propertyName: "+propertyName);
//是否聲明了propertyName的屬性和get方法
if (metaObject.hasGetter(propertyName)) {
Object obj = metaObject.getValue(propertyName);
sql = sql.replaceFirst("\\?", getParameterValue(obj));
} else if (boundSql.hasAdditionalParameter(propertyName)) {
//判斷是不是sql的附加參數(shù)
Object obj = boundSql.getAdditionalParameter(propertyName);
sql = sql.replaceFirst("\\?", getParameterValue(obj));
}
}
}
}
return sql;
}
}
在MybatisPlusConfig中注冊(cè)bean
@Bean
@ConditionalOnMissingBean //有此實(shí)例便不進(jìn)行注冊(cè)
public SqlLogsInterceptor dataScopeInterceptor(DataSource dataSource) {
return new SqlLogsInterceptor(dataSource);
}
使用注解
@SqlLogs(hasSqlLog = true)
List<XgYyxxVo> selectByLqw(@Param(Constants.WRAPPER) Wrapper queryWrapper);
2.詳細(xì)關(guān)于mybatis攔截器:
https://www.cnblogs.com/top-sky-hua/p/11306376.html