mybatis filter 怎么能获取到执行的sql语句 给出具体代码
时间: 2024-05-08 07:18:26 浏览: 74
Mybatis控制台打印Sql语句的实现代码
可以通过Mybatis提供的拦截器(Interceptor)来实现获取执行的SQL语句。具体代码如下:
1.编写自定义的拦截器实现Interceptor接口:
```
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import java.util.Properties;
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MyInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = invocation.getArgs()[1];
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
String sql = boundSql.getSql();
System.out.println("执行的SQL语句为:" + sql);
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
```
2.在Mybatis配置文件中配置拦截器:
```
<plugins>
<plugin interceptor="com.example.MyInterceptor"/>
</plugins>
```
这样,在执行任何一条SQL语句时,都会通过自定义的拦截器进行拦截并输出执行的SQL语句。
阅读全文