本文主要是讲通过 MyBaits 的 Interceptor
的拓展点进行对 MyBatis 执行 SQL 之前做一个逻辑拦截实现自定义逻辑的插入执行。
适合场景:
1. 比如限制数据库查询最大访问条数;
2. 限制登录用户只能访问当前机构数据。
定义是否开启注解
定义是否开启注解, 主要做的一件事情就是是否添加 SQL 拦截器。
// 全局开启
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MyBatisSqlInterceptorConfiguration.class)
public @interface EnableSqlInterceptor {
}
// 自定义注解
@Target({ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface DataScope {
}
复制代码
注册SQL 拦截器
注册一个 SQL 拦截器,会对符合条件的 SQL 查询操作进行拦截。
public class MyBatisSqlInterceptorConfiguration implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
sqlSessionFactory.getConfiguration().addInterceptor(new MyBatisInterceptor());
}
}
复制代码
处理逻辑
在处理逻辑中,我主要是做一个简单的 limit 1
案例,如果是自己需要做其他的逻辑需要修改
@Slf4j
@Intercepts(
{
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class,