智慧屏安装APP的最佳实践与跨平台小程序开发的结合
872
2023-06-19
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......");
// 获取http://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)http:// {
}
// 复制原始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;
}
}
}
这样重启访问即可发现每次查询都会走这边!
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~