国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

SpringBoot整合MybatisSQL過濾@Intercepts的實現(xiàn)

瀏覽:5日期:2023-05-28 15:19:13

場景:

系統(tǒng)模塊查詢數(shù)據(jù)庫需要根據(jù)用戶的id去篩選數(shù)據(jù)。那么如果在 每個sql加user_id的過濾顯然不明確。所以要在查詢前將sql拼接上條件,做統(tǒng)一管理。

開發(fā)環(huán)境:

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; }// 繼續(xù)執(zhí)行 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; } }}

這樣重啟訪問即可發(fā)現(xiàn)每次查詢都會走這邊!

到此這篇關于SpringBoot整合MybatisSQL過濾@Intercepts的實現(xiàn)的文章就介紹到這了,更多相關SpringBoot MybatisSQL過濾@Intercepts內容請搜索好吧啦網以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 九江县| 余姚市| 扎鲁特旗| 资源县| 曲周县| 瑞金市| 克山县| 永登县| 阳原县| 宾阳县| 双桥区| 牡丹江市| 宁蒗| 文登市| 方正县| 岑巩县| 尼玛县| 中卫市| 营山县| 富源县| 连平县| 阿拉善左旗| 壶关县| 航空| 乡城县| 东山县| 江达县| 榆树市| 化州市| 新疆| 自治县| 阜宁县| 阜阳市| 启东市| 竹山县| 涟源市| 讷河市| 丘北县| 喀喇沁旗| 运城市| 普安县|