mybatis通过拦截器获取sql语句,操作类型,数据库链接URL,库名,表名,处理字段名
mybatis通过拦截器获取sql语句,操作类型,数据库链接URL,库名,表名,处理字段名
·
@Intercepts({
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
})
public class AcesInterceptor implements Interceptor {
private Properties properties = new Properties();
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
// 获取操作类型
String sqlCommandType = mappedStatement.getSqlCommandType().name();
if ("INSERT".equals(sqlCommandType)) {
Object parameterObject = invocation.getArgs().length > 1 ? invocation.getArgs()[1] : null;
// 获取 SQL 语句
BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
String sql = boundSql.getSql();
// 获取数据库连接信息
Connection connection = mappedStatement.getConfiguration().getEnvironment().getDataSource().getConnection();
String url = connection.getMetaData().getURL();
String catalog = connection.getCatalog();
String tableName = extractTableName(sql);
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
for (ParameterMapping p:parameterMappings) {
if (p.getTypeHandler() instanceof AcesCipherTextHandle){
MetaDataInfo metaDataInfo = new MetaDataInfo();
metaDataInfo.setDbHost(url);
metaDataInfo.setCatalogName(catalog);
metaDataInfo.setBoundSql(sql);
metaDataInfo.setTableName(tableName);
metaDataInfo.setColumnName(p.getProperty());
MqEventWork.getIns().addMQ(metaDataInfo);
}
}
}
}catch (Exception e){
}
// 继续执行拦截链中的下一个拦截器
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
//获取代理权
if ((properties.getProperty("enable").equals("true")) && target instanceof Executor) {
//如果是Executor(执行增删改查操作),否则拦截下来
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties properties) {
// 接收配置属性
this.properties = properties;
}
// 提取表名的逻辑
private String extractTableName(String sql) {
int startIndex = sql.toLowerCase().indexOf("insert into") + 11;
int endIndex = sql.indexOf("(", startIndex);
return sql.substring(startIndex, endIndex).trim();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<plugins>
<plugin interceptor=".interceptor.AcesInterceptor">
<property name="enable" value="false"/>
</plugin>
</plugins>
</configuration>
更多推荐
已为社区贡献1条内容
所有评论(0)