一、问题描述
有时候在使用mybatis/mybatis plus过程中,需要用到一些全局变量,方便维护,比如表名前缀,为整个项目使用统一的表前缀,将它定义为一个变量,在xml中直接使用就行了,这就省去了很多事。
二、解决方法
有以下2中方式可以实现:
方法一
mybatis/mybatis plus默认就支持全局变量,可通过如下方式配置:
mybatis-plus配置:
mybatis-plus:
typeAliasesPackage: com.xxx.entity
mapperLocations: classpath*:mapper/*.xml
configurationProperties:
tablePrefix: test_ # 自定义sql中表名带前缀
mybatis配置:
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.xxx
configuration:
variables:
tablePrefix: test_
在xml中直接通过${}就能取到
<select id="selectListAll" resultType="com.xxx.User">
select * from ${tablePrefix}main_user
</select>
这种方式有个问题就是,在项目启动后,会先将定义的全局变量替换掉,替换的位置在
org.apache.ibatis.parsing.XNode的构造方法中
parseBody方法将会替换掉${tablePrefix}占位符
也就是说,该方法是在项目启动后操作的。
方法二
上面的方式是在启动后就全部替换了,而有时候,我们需要在运行的过程中动态传入固定变量,这时候,上面的方法就不适用了,有没有方法可以动态的设置运行时全局参数?有的,查看源码你会发现,最终在解析动态SQL时,在org.apache.ibatis.scripting.xmltags.TextSqlNode.BindingTokenParser#handleToken方法中都会调用DynamicContext ,只要我们在执行相关操作之前,将参数设置进去就能实现手动全局参数注入,
如何实现了?在mybatis中提供了插件机制,使用它就能搞定,看下mybatis的plugin文档,他能对一些操作进行拦截,这不就是我们想要的结果吗,我们可以自定义了一个插件,完整代码如下:
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.core.toolkit.TableNameParser;
import com.baomidou.mybatisplus.extension.parser.JsqlParserSupport;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.scripting.xmltags.DynamicContext;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
/**
* @version: V1.0
* @author: mszf
* @date: 2022-02-08 23:08
* @description: 全局参数注入
*/
@Slf4j
@Intercepts({ @Signature(method = "update", args = { MappedStatement.class, Object.class }, type = Executor.class),
@Signature(method = "query", args = { MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class }, type = Executor.class) })
public class GlobalParametersInterceptor implements Interceptor {
private Set<Integer> sourceStorage = new HashSet<Integer>();
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement mappedStatement = (MappedStatement) args[0];
SqlSource sqlSource = mappedStatement.getSqlSource();
// 只拦截动态sql
if (sqlSource instanceof DynamicSqlSource) {
// 获取到sqlNode对象
Field field = DynamicSqlSource.class.getDeclaredField("rootSqlNode");
field.setAccessible(true);
SqlNode sqlnode = (SqlNode) field.get(sqlSource);
if (!sourceStorage.contains(sqlSource.hashCode())) {
// 获取动态代理对象
SqlNode proxyNode = proxyNode(sqlnode);
field.set(sqlSource, proxyNode);
sourceStorage.add(sqlSource.hashCode());
}
}
return invocation.proceed();
}
private SqlNode proxyNode(SqlNode sqlnode) {
SqlNode proxyNode = (SqlNode) Proxy.newProxyInstance(sqlnode.getClass().getClassLoader(),
new Class[]{SqlNode.class}, new SqlNodeInvocationHandler(sqlnode));
return proxyNode;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
private class SqlNodeInvocationHandler implements InvocationHandler {
private final SqlNode target;
public SqlNodeInvocationHandler(SqlNode target) {
super();
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Setting setting = SettingUtils.readInstallSetting();
DynamicContext context = (DynamicContext) args[0];
//手动添加
context.getBindings().put("tablePrefix","xxxxxx");
return method.invoke(target, args);
}
}
}
注入到spring中就可以了
@Bean
public GlobalParametersInterceptor globalParametersInterceptor(){
return new GlobalParametersInterceptor();
}