Get Table Names in MyBatis Interceptor
MyBatis Interceptor is a mechanism provided by MyBatis that allows for intercepting and handling before and after the execution of SQL statements. To retrieve the table name in the Interceptor, you can use the following method:
In the intercept method of Interceptor, we can obtain the BoundSql object, which contains the executed SQL statement and parameter information.
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
BoundSql boundSql = mappedStatement.getBoundSql(invocation.getArgs()[1]);
String sql = boundSql.getSql();
// 获取表名
String tableName = extractTableName(sql);
return invocation.proceed();
}
Write a method to extract table names from SQL statements, which can be achieved through regular expressions or other methods.
private String extractTableName(String sql) {
String tableName = null;
Pattern pattern = Pattern.compile("FROM\\s+([^\\s]+)\\s*|JOIN\\s+([^\\s]+)\\s*|UPDATE\\s+([^\\s]+)\\s*|INTO\\s+([^\\s]+)\\s*");
Matcher matcher = pattern.matcher(sql);
while (matcher.find()) {
tableName = matcher.group(1);
if (StringUtils.isNotBlank(tableName)) {
break;
}
}
return tableName;
}
Configure Interceptors in the MyBatis configuration file, and apply them to the desired Mapper or Statement.
<plugins>
<plugin interceptor="com.example.MyInterceptor">
<!-- 配置Interceptor -->
</plugin>
</plugins>
By following the above steps, it is possible to retrieve the executed SQL statement in MyBatis Interceptor and extract the table name from it.