
项目没有使用MyBatis,进行数据操作时使用的是jdbc中默认的schema,现在项目要加入多租户,同一个数据库下不同租户使用不同的实例schema,这就要在mapper文件内所有的表名称前加上schema,并动态传递其参数值,这样每个SQL都要添加这个参数,如果传递的是对象,也要给对象加相应的属性,这个工作量可想而知。==必须想办法,将schema参数传递给所有的SQL,办法就是全局配置。==
拦截器【 :one: SchemaInterceptor】实现(如果用户调用的SQL接口里没有传 schemaName 就用默认值):
@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 SchemaInterceptor implements Interceptor {
/**
* 这里没有打印日志
*/
private static Log LOG = LogFactory.getLog(SchemaInterceptor.class);
/**
* mapper.xml 使用SCHEMA时的参数名称
*/
private static final String SCHEMA = "schemaName";
/**
* 设置默认的schema
*/
private String schema = "public";
/**
* 拦截到的动态SQL处理后放入此对象
*/
private Set<Integer> sourceStorage = new HashSet<>();
@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())) {
// 获取动态代理对象
Map<String, Object> argMap = (HashMap<String, Object>) args[1];
// 判断是否传递 schemaName或schema 如果已经传递则使用用户传递的值 否则使用默认值
String schemaNameStr = "schemaName", schemaStr = "schema";
if (StringUtils.isEmpty(MapUtils.getString(argMap, schemaNameStr)) && StringUtils.isEmpty(MapUtils.getString(argMap, schemaStr))) {
SqlNode proxyNode = proxyNode(sqlNode);
field.set(sqlSource, proxyNode);
}
sourceStorage.add(sqlSource.hashCode());
}
}
return invocation.proceed();
}
/**
* 通过动态代理对象 添加schema参数
*
* @param sqlNode SQL节点
* @return SqlNode
*/
private SqlNode proxyNode(SqlNode sqlNode) {
return (SqlNode) Proxy.newProxyInstance(sqlNode.getClass().getClassLoader(),
new Class[]{SqlNode.class}, new SqlNodeInvocationHandler(sqlNode));
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
LOG.debug("setProperties====>" + properties);
}
private class SqlNodeInvocationHandler implements InvocationHandler {
private SqlNode target;
SqlNodeInvocationHandler(SqlNode target) {
super();
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
DynamicContext context = (DynamicContext) args[0];
// 给schema添加.
setSchema(schema);
// 设置schema
context.getBindings().put(SCHEMA, schema);
return method.invoke(target, args);
}
}
/**
* 给schema 添加.
*
* @param schema schemaName
*/
private void setSchema(String schema) {
String pointStr = ".";
if (StringUtils.isNotBlank(schema)) {
if (!schema.endsWith(pointStr)) {
schema += pointStr;
}
}
this.schema = schema;
}
}拦截器【 :two: 注册】给 SqlSessionFactoryBean 添加插件:
@Bean(name = "sqlSessionFactory_greenplum")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource_greenplum") DataSource dataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
// 设置数据源参数
sessionFactory.setDataSource(dataSource);
// mapper路径和mybatis配置文件路径
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(GreenplumConfiguration.MAPPER_LOCATION));
sessionFactory.setConfigLocation(new ClassPathResource(mybatisConfigPath));
// 添加自定义的schema拦截器【此次配置的重点】
sessionFactory.setPlugins(new Interceptor[]{new SchemaInterceptor()});
return sessionFactory.getObject();
}注入【 :three: mapper.xml】这里使用 ${schemaName} 获取配置的 schema 的值:
<!--执行插入文件数据SQL-->
<insert id="insertFileData" parameterType="map">
insert into ${schemaName}${target_table}( ${table_field} ) VALUES ( ${field_value} )
</insert>首先要注意的是,这里用的不是SpringMVC里的拦截器,而是mybatis的拦截器,拦截器是在执行mapper文件内的SQL前触发的,此时,如果你传递了schema参数,拦截器就不会覆盖schema的值,如果没有配置,则使用配置的默认值。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。