場景:spring
系統模塊查詢數據庫須要根據用戶的id去篩選數據。那麼若是在 每一個sql加user_id的過濾顯然不明確。因此要在查詢前將sql拼接上條件,作統一管理。
開發環境: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; } } }
這樣重啓訪問便可發現每次查詢都會走這邊!mybatis