平常我们写项目时应该都会遇到这么一个问题,一些接口需要根据账号权限的不同而展示不同的数据,又或者是SaaS化产品的租户,一般遇到这种情况,我们在写查询语句的时候,会加上相应的SQL来过滤掉不符合的数据,这样当然是可行的,但是基本上SQL都是相同的,所以就会造成会有很多重复的SQL片段,这样看起来也不太雅观,那有什么方法可以不写这么多重复的SQL吗?
答案当然是可以的,也就是这次的主题mybatis拦截器,通过拦截器,我们可以拦截到即将运行的SQL,然后动态修改SQL,将过滤条件添加上去,这样我们在编写SQL的时候就不需要考虑数据权限的问题了,只需要在需要进行数据过滤的方法上加上一个自定义的注解,就可以完成数据的过滤操作了。
说了这么多,那mybatis拦截器又是什么东西呢?顾名思义,拦截器,自然就是拦截某些东西了,而mybatis提供的这个拦截器,就是用来拦截即将要运行的SQL了,接下来就来简单了解一下拦截器吧。
概念了解
在创建拦截器之前,我们先来了解2个注解:@Intercepts
和@Signature
上面这两个注解是写在拦截器类的上面的,主要是用来声明这是一个拦截器以及用来拦截什么
先说说@Intercepts
吧,这个注解源码如下:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Intercepts {
Signature[] value();
}
可以看到只有一个参数value,而这个参数则是一个@Signature
数组,里面主要是用来放@Signature
的,那@Signature
又是干嘛用的呢,看看@Signature
的源码:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Signature {
Class<?> type();
String method();
Class<?>[] args();
}
里面有3个参数,分别是type、method、args。
type指的是拦截类型,目前只有四种类型:Executor、StatementHandler、ParameterHandler、ResultSetHandler
这四种类型如下:
org.apache.ibatis.executor.Executor // 用于拦截指定的方法(如query、update、commit等,详细的可以自行去查看)
org.apache.ibatis.executor.statement.StatementHandler // 拦截SQL语法的构建,也就是说SQL是在这里构建的
org.apache.ibatis.executor.parameter.ParameterHandler // 拦截SQL的参数,也就是我们会传递给SQL中 ?的参数
org.apache.ibatis.executor.resultset.ResultSetHandler // 拦截结果集,就是执行SQL后返回的结果
method指的是方法,也就是即上面4种类型中的方法
args则是方法的参数,因为会有重载方法,所以需要指定参数才能知道是哪一个
注解了解了,接下来是接口Interceptor
这个接口里面有三个方法,最重要的就是里面的intercept(Invocation invocation)
方法了,我们就是重写这个方法来实现SQL的修改的。
接着是Invocation
这个类,通过这个类,我们可以拿到MappedStatement
,这个就存着我们的SQL,我们就是通过修改这里面的SQL来实现目的的,具体的用法可以看下面的使用。
使用实例
概念了解了,接下来就是如何去使用了,mybatis拦截器用起来也相当简单。
1、引入依赖
使用之前自然是需要引入mybatis的依赖的,这里我使用的是mybatis-plus
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.2version>
dependency>
2、创建拦截器
引入依赖后就是创建自己的拦截器了,大体的框架如下:
@Intercepts({
// 这里可以加入多个@Signature,主要看自己的需求,我这里一个就够了
@Signature(
type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)
})
public class MyInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
// todo
return invocation.proceed();
}
}
3、注册拦截器
拦截器创建好了,接下来要告诉mybatis使用我们的拦截器了
@Configuration
@MapperScan("club.gggd.demo.mapper")
public class MybatisPlusConfig {
@Bean
public MyInterceptor getMyInterceptor() {
MyInterceptor myInterceptor = new MyInterceptor();
return myInterceptor;
}
}
4、创建注解
这一步就比较自由了,主要看大家的需求是怎样的,我这里就稍微弄个简单点的,注解里有一个参数,这个参数会拼接到原来的SQL上
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SqlAnno {
// 需要加上的SQL
String sql();
}
5、编辑SQL
这一步就是重头戏了,在这一步我们需要拿到原先的SQL,并将原先的SQL进行改造成新的SQL,然后将新的SQL放进去执行。
@Intercepts({
@Signature(
type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)
})
public class MyInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 拿到运行SQL的mappedStatement
MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
// 判断是否是select
if (!"SELECT".equals(mappedStatement.getSqlCommandType().name())) {
return invocation.proceed();
}
// 拿到类名,方法名以及class
String nameSpace = mappedStatement.getId();
String classPath = nameSpace.substring(0, nameSpace.lastIndexOf("."));
String methodName = nameSpace.substring(nameSpace.lastIndexOf(".") + 1);
Class<?> clazz = Class.forName(classPath);
// 拿到该类的全部方法,并找到上面的方法,这个方法也就是本次即将要运行的SQL对应的方法
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
// 注意,这里不能分辨出重载方法,所以尽量不要有方法名相同的方法
if (methodName.equals(method.getName())) {
// 判断是否有注解
SqlAnno annotation = method.getAnnotation(SqlAnno.class);
if (annotation == null) {
return invocation.proceed();
}
// 获取到注解后,可以拿到注解的信息
String addSql = annotation.sql();
System.out.println("addSql--->" + addSql);
// 获取原始SQL
BoundSql boundSql = mappedStatement.getBoundSql(invocation.getArgs()[1]);
String sql = boundSql.getSql();
System.out.println("sql--->" + sql);
// 修改SQL,这里可以根据业务来,比如拿到当前用户的权限信息,根据权限信息拼装SQL
String newSql = sql + addSql;
System.out.println("newSql--->" + newSql);
// 处理SQL
sqlHandle(mappedStatement, new MySqlSource(boundSql), invocation, newSql);
break;
}
}
System.out.println("finalSql--->" + ((MappedStatement) invocation.getArgs()[0]).getBoundSql(invocation.getArgs()[1]).getSql());
return invocation.proceed();
}
/**
* 处理SQL
* @param ms
* @param sqlSource
* @param invocation
* @param newSql
*/
private void sqlHandle(MappedStatement ms, SqlSource sqlSource, Invocation invocation, String newSql) {
// 组装 MappedStatement
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), sqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
StringBuilder keyProperties = new StringBuilder();
for (String keyProperty : ms.getKeyProperties()) {
keyProperties.append(keyProperty).append(",");
}
keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
builder.keyProperty(keyProperties.toString());
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.resultSetType(ms.getResultSetType());
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
MappedStatement newMappedStatement = builder.build();
MetaObject metaObject = MetaObject.forObject(newMappedStatement, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
metaObject.setValue("sqlSource.boundSql.sql", newSql);
invocation.getArgs()[0] = newMappedStatement;
}
// 定义一个内部类,作用是包装sql
class MySqlSource implements SqlSource {
private BoundSql boundSql;
public MySqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
@Override
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
}
6、使用
接下来只需要在需要进行数据权限的方法上加上注解就可以啦,注意要放在mapper层的方法上哦
@Mapper
public interface AdminMapper extends BaseMapper<Admin> {
@SqlAnno(sql = " and tel like '19%'")
Admin get(int id);
@SqlAnno(sql = " where tel like '19%'")
List<Admin> getAll();
}