SpringBoot整合MybatisSQL过滤@Intercepts的实现

时间:2021-05-20

场景:

系统模块查询数据库需要根据用户的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的实现的文章就介绍到这了,更多相关SpringBoot MybatisSQL过滤@Intercepts内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章