SpringBoot整合MybatisSQL过滤@Intercepts

场景:

 系统模块查询数据库需要根据用户的id去筛选数据。那么如果在  每个sql加user_id的过滤显然不明确。所以要在查询前将sql拼接上条件,做统一管理。

开发环境:

  spring boot + mybatis

只需一个拦截类即可搞定(在看代码前需要了解注解@Intercepts()):

@Component
@Intercepts({ @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })
public class SqlInterceptor implements Interceptor {

    private Logger logger =  LoggerFactory.getLogger(SqlInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
 logger.info("Interceptor......");
//        获取sql
 MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
 Object parameter = invocation.getArgs()[1];
 BoundSql boundSql = mappedStatement.getBoundSql(parameter);
 String oldsql = boundSql.getSql();
 logger.info("old:"+oldsql);

//        判断sql是否有where条件。改变sql。
 boolean status = oldsql.toLowerCase().contains("where");

 if (status) {
     BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), oldsql + " and 1=1",
             boundSql.getParameterMappings(), boundSql.getParameterObject());
     MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
     invocation.getArgs()[0] = newMs;
 }
// 继续执行
 Object result = invocation.proceed();
 return result;
    }

    @Override
    public Object plugin(Object target) {
 return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    // 复制原始MappedStatement
    private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
 MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource,
         ms.getSqlCommandType());
 builder.resource(ms.getResource());
 builder.fetchSize(ms.getFetchSize());
 builder.statementType(ms.getStatementType());
 builder.keyGenerator(ms.getKeyGenerator());
 if (ms.getKeyProperties() != null) {
     for (String keyProperty : ms.getKeyProperties()) {
         builder.keyProperty(keyProperty);
     }
 }
 builder.timeout(ms.getTimeout());
 builder.parameterMap(ms.getParameterMap());
 builder.resultMaps(ms.getResultMaps());
 builder.cache(ms.getCache());
 builder.useCache(ms.isUseCache());
 return builder.build();
    }

    public static class BoundSqlSqlSource implements SqlSource {
 BoundSql boundSql;

 public BoundSqlSqlSource(BoundSql boundSql) {
     this.boundSql = boundSql;
 }

 public BoundSql getBoundSql(Object parameterObject) {
     return boundSql;
 }
    }

}

这样重启访问即可发现每次查询都会走这边!

你可能感兴趣的:(SpringBoot整合MybatisSQL过滤@Intercepts)