您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“如何實(shí)現(xiàn)MyBatis自定義SQL攔截器”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“如何實(shí)現(xiàn)MyBatis自定義SQL攔截器”吧!
定義是否開啟注解, 主要做的一件事情就是是否添加 SQL 攔截器。
// 全局開啟 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Import(MyBatisSqlInterceptorConfiguration.class) public @interface EnableSqlInterceptor { } // 自定義注解 @Target({ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface DataScope { }
注冊(cè)一個(gè) SQL 攔截器,會(huì)對(duì)符合條件的 SQL 查詢操作進(jìn)行攔截。
public class MyBatisSqlInterceptorConfiguration implements ApplicationContextAware { @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class); sqlSessionFactory.getConfiguration().addInterceptor(new MyBatisInterceptor()); } }
在處理邏輯中,我主要是做一個(gè)簡(jiǎn)單的 limit 1 案例,如果是自己需要做其他的邏輯需要修改
@Slf4j @Intercepts( { @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}), }) public class MyBatisInterceptor implements Interceptor { private static final Logger LOGGER = LoggerFactory.getLogger(MyBatisInterceptor.class); @Override public Object intercept(Invocation invocation) throws Throwable { // TODO Auto-generated method stub Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; Executor executor = (Executor) invocation.getTarget(); CacheKey cacheKey; BoundSql boundSql; //由于邏輯關(guān)系,只會(huì)進(jìn)入一次 if (args.length == 4) { //4 個(gè)參數(shù)時(shí) boundSql = ms.getBoundSql(parameter); cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql); } else { //6 個(gè)參數(shù)時(shí) cacheKey = (CacheKey) args[4]; boundSql = (BoundSql) args[5]; } DataScope dataScope = getDataScope(ms); if (Objects.nonNull(dataScope)) { String origSql = boundSql.getSql(); log.info("origSql : {}", origSql); // 組裝新的 sql // todo you weaving business String newSql = origSql + " limit 1"; // 重新new一個(gè)查詢語句對(duì)象 BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql, boundSql.getParameterMappings(), boundSql.getParameterObject()); // 把新的查詢放到statement里 MappedStatement newMs = newMappedStatement(ms, new BoundSqlSource(newBoundSql)); for (ParameterMapping mapping : boundSql.getParameterMappings()) { String prop = mapping.getProperty(); if (boundSql.hasAdditionalParameter(prop)) { newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop)); } } args[0] = newMs; if (args.length == 6) { args[5] = newMs.getBoundSql(parameter); } } LOGGER.info("mybatis intercept sql:{},Mapper方法是:{}", boundSql.getSql(), ms.getId()); return invocation.proceed(); } private MappedStatement newMappedStatement(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 && ms.getKeyProperties().length > 0) { builder.keyProperty(ms.getKeyProperties()[0]); } builder.timeout(ms.getTimeout()); builder.parameterMap(ms.getParameterMap()); builder.resultMaps(ms.getResultMaps()); builder.resultSetType(ms.getResultSetType()); builder.cache(ms.getCache()); builder.flushCacheRequired(ms.isFlushCacheRequired()); builder.useCache(ms.isUseCache()); return builder.build(); } private DataScope getDataScope(MappedStatement mappedStatement) { String id = mappedStatement.getId(); // 獲取 Class Method String clazzName = id.substring(0, id.lastIndexOf('.')); String mapperMethod = id.substring(id.lastIndexOf('.') + 1); Class<?> clazz; try { clazz = Class.forName(clazzName); } catch (ClassNotFoundException e) { return null; } Method[] methods = clazz.getMethods(); DataScope dataScope = null; for (Method method : methods) { if (method.getName().equals(mapperMethod)) { dataScope = method.getAnnotation(DataScope.class); break; } } return dataScope; } @Override public Object plugin(Object target) { // TODO Auto-generated method stub LOGGER.info("MysqlInterCeptor plugin>>>>>>>{}", target); return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { // TODO Auto-generated method stub String dialect = properties.getProperty("dialect"); LOGGER.info("mybatis intercept dialect:>>>>>>>{}", dialect); } /** * 定義一個(gè)內(nèi)部輔助類,作用是包裝 SQL */ class BoundSqlSource implements SqlSource { private BoundSql boundSql; public BoundSqlSource(BoundSql boundSql) { this.boundSql = boundSql; } public BoundSql getBoundSql(Object parameterObject) { return boundSql; } } }
我們?cè)?XXXMapper 中對(duì)應(yīng)的數(shù)據(jù)操作方法只要加入 @DataScope 注解即可。
@Mapper public interface OrderMapper { @Select("select 1 ") @DataScope Intger selectOne(); }
到此,相信大家對(duì)“如何實(shí)現(xiàn)MyBatis自定義SQL攔截器”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。