写在前面
今天收到一个需求,根据请求方的不同,动态的切换表名(涵盖SELECT,INSERT,UPDATE操作)。几张新表和旧表的结构完全一致,但是分开维护。看到需求第一反应是将表名提出来当${tableName}参数,然后AOP拦截判断再替换表名。但是后面看了一下这几张表在很多mapper接口都有使用,其中还有一些复杂的连接查询,提取tableName当参数肯定是不现实的了。后面和组内大佬讨论之后,发现可以使用MyBatis提供的拦截器,判断并且动态的替换表名。
一、Mybatis Interceptor 拦截器接口和注解
简单的说就是mybatis在执行sql的时候,拦截目标方法并且在前后加上我们的业务逻辑。实际上就是加@Intercepts注解和实现 org.apache.ibatis.plugin.Interceptor 接口
1 2 3 4 5 6 |
@Intercepts ( @Signature (method = "query" , type = Executor. class , args = {MappedStatement. class , Object. class , RowBounds. class , ResultHandler. class } ) ) |
1 2 3 4 5 6 7 8 9 10 |
public interface Interceptor { //主要重写这个方法、实现我们的业务逻辑 Object intercept(Invocation invocation) throws Throwable;
//生成代理对象,可以在这里判断是否生成代理对象 Object plugin(Object target);
//如果我们拦截器需要用到一些变量参数,可以在这里读取 void setProperties(Properties properties); } |
二、实现思路
在intercept方法中有参数Invocation对象,里面有3个成员变量和@Signature对应target | Object | 代理对象 |
method | Method | 被拦截方法 |
args | Object[] | 被拦截方法执行所需的参数 |
三、代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.plugin.*; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds;
import java.util.*;
/** * @description: 动态替换表名拦截器 * @author: hinotoyk * @created: 2022/04/19 */ //method = "query"拦截select方法、而method = "update"则能拦截insert、update、delete的方法 @Intercepts ({ @Signature (type = Executor. class , method = "query" , args = {MappedStatement. class , Object. class , RowBounds. class , ResultHandler. class }), @Signature (type = Executor. class , method = "update" , args = {MappedStatement. class , Object. class }) }) public class ReplaceTableInterceptor implements Interceptor { private final static Map<String,String> TABLE_MAP = new LinkedHashMap<>(); static { //表名长的放前面,避免字符串匹配的时候先匹配替换子集 TABLE_MAP.put( "t_game_partners" , "t_game_partners_test" ); //测试 TABLE_MAP.put( "t_file_recycle" , "t_file_recycle_other" ); TABLE_MAP.put( "t_folder" , "t_folder_other" ); TABLE_MAP.put( "t_file" , "t_file_other" ); }
@Override public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); //获取MappedStatement对象 MappedStatement ms = (MappedStatement) args[ 0 ]; //获取传入sql语句的参数对象 Object parameterObject = args[ 1 ];
BoundSql boundSql = ms.getBoundSql(parameterObject); //获取到拥有占位符的sql语句 String sql = boundSql.getSql(); System.out.println( "拦截前sql :" + sql);
//判断是否需要替换表名 if (isReplaceTableName(sql)){ for (Map.Entry<String, String> entry : TABLE_MAP.entrySet()){ sql = sql.replace(entry.getKey(),entry.getValue()); } System.out.println( "拦截后sql :" + sql);
//重新生成一个BoundSql对象 BoundSql bs = new BoundSql(ms.getConfiguration(),sql,boundSql.getParameterMappings(),parameterObject);
//重新生成一个MappedStatement对象 MappedStatement newMs = copyMappedStatement(ms, new BoundSqlSqlSource(bs));
//赋回给实际执行方法所需的参数中 args[ 0 ] = newMs; } return invocation.proceed(); }
@Override public Object plugin(Object target) { return Plugin.wrap(target, this ); }
@Override public void setProperties(Properties properties) { }
/*** * 判断是否需要替换表名 * @param sql * @return */ private boolean isReplaceTableName(String sql){ for (String tableName : TABLE_MAP.keySet()){ if (sql.contains(tableName)){ return true ; } } return false ; }
/*** * 复制一个新的MappedStatement * @param ms * @param newSqlSource * @return */ private MappedStatement copyMappedStatement (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(String.join( "," ,ms.getKeyProperties())); } 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(); }
/*** * MappedStatement构造器接受的是SqlSource * 实现SqlSource接口,将BoundSql封装进去 */ public static class BoundSqlSqlSource implements SqlSource { private BoundSql boundSql; public BoundSqlSqlSource(BoundSql boundSql) { this .boundSql = boundSql; } @Override public BoundSql getBoundSql(Object parameterObject) { return boundSql; } } } |
四、运行结果
写在最后
一开始接到这个需求的时候,会习惯性的从熟悉常用的技术入手。如果涉及的表引用没这么多,是不是就会直接用AOP拦截判断替换了呢,我大概率是会的。可能就不会想到上面的拦截器动态替换的方法(相当于失去一次学习的机会),还是要跳出惯性多思考还有没有更合适的做法,把每次需求都当成一次学习的机会,舒适圈都能变开阔很多,共勉。
参考资料
MyBatis官网
mybatis插件实现自定义改写表名
到此这篇关于MyBatis拦截器动态替换表名的文章就介绍到这了,更多相关MyBatis动态替换表名内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://juejin.cn/post/7089370703547334686
查看更多关于MyBatis拦截器动态替换表名的方法详解的详细内容...