How to implement SQL interceptor in MyBatis Plus?
To implement SQL interceptor in Mybatis Plus, you can follow these steps:
- a person or thing that intercepts
- Interceptor for MySql
public class MySqlInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 拦截 SQL 执行前的操作
// ...
// 调用原始的方法
Object result = invocation.proceed();
// 拦截 SQL 执行后的操作
// ...
return result;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// 设置拦截器的属性
// ...
}
}
- configuration file for MyBatis Plus
<configuration>
<interceptors>
<interceptor>
<typeHandlers>
<typeHandler handler="com.example.MySqlInterceptor"/>
</typeHandlers>
</interceptor>
</interceptors>
</configuration>
- Configure interceptors in the MyBatis Plus configuration class.
@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
@Bean
public Interceptor mySqlInterceptor() {
return new MySqlInterceptor();
}
@Autowired
private Interceptor mySqlInterceptor;
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(mySqlInterceptor);
return interceptor;
}
}
In this way, MySqlInterceptor will intercept SQL operations executed in Mybatis Plus. You can implement specific interception logic in the intercept method, such as recording SQL execution time and modifying SQL conditions.