@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }), })
public class MybatisInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = null;
if (invocation.getArgs().length > 1) {
parameter = invocation.getArgs()[1];
}
LoginUser user = LoginUser.getLoginUser();
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null && parameterMappings.size() > 0) {
Configuration configuration = mappedStatement.getConfiguration();
Object parameterObject = boundSql.getParameterObject();
MetaObject metaObject = configuration.newMetaObject(parameterObject);
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = parameterMapping.getProperty();
if (metaObject.hasGetter(propertyName)) {
Object obj = metaObject.getValue(propertyName);
String columValue = "";
if (obj != null && obj.toString().length() > 1000) {
columValue = obj.toString().substring(0, 999);
} else if (obj != null && obj.toString().length() < 1000) {
columValue = obj.toString();
}
sql = sql.replaceFirst("\\?", columValue);
} else if (boundSql.hasAdditionalParameter(propertyName)) {
Object obj = boundSql.getAdditionalParameter(propertyName);
String columValue = "";
if (obj != null && obj.toString().length() > 1000) {
columValue = obj.toString().substring(0, 999);
} else if (obj != null && obj.toString().length() < 1000) {
columValue = obj.toString();
}
sql = sql.replaceFirst("\\?", columValue);
}
}
}
log.info("SQL: {} , user: {}, date : {}", sql, null != user ? user.getName() : "", new Date());
if (!sql.contains("tbl_sys_operation_log")) {
DboSysOperationLog log = new DboSysOperationLog();
if (user != null) {
log.setUserId(user.getId());
} else {
log.setUserId(8505);
}
log.setSqlText(sql);
log.setOperateTime(new Date());
log.setModuleName("maintenance");
DboSysOperationLogService.insert(log);
}
} catch (Exception e) {
e.printStackTrace();
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
使用拦截器进行SQL的拦截保存