why
??项目没有使用MyBatis,进行数据操作时使用的是jdbc中默认的schema,现在项目要加入多租户,同一个数据库下不同租户使用不同的实例schema,这就要在mapper文件内所有的表名称前加上schema,并动态传递其参数值,这样每个SQL都要添加这个参数,如果传递的是对象,也要给对象加相应的属性,这个工作量可想而知。 ??必须想办法,将schema参数传递给所有的SQL,办法就是全局配置。
code
拦截器【 1?? 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);
private static final String SCHEMA = "schemaName";
private String schema = "public";
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();
if (sqlSource instanceof DynamicSqlSource) {
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];
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();
}
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];
setSchema(schema);
context.getBindings().put(SCHEMA, schema);
return method.invoke(target, args);
}
}
private void setSchema(String schema) {
String pointStr = ".";
if (StringUtils.isNotBlank(schema)) {
if (!schema.endsWith(pointStr)) {
schema += pointStr;
}
}
this.schema = schema;
}
}
拦截器【 2?? 注册】给 SqlSessionFactoryBean 添加插件:
@Bean(name = "sqlSessionFactory_greenplum")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource_greenplum") DataSource dataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(GreenplumConfiguration.MAPPER_LOCATION));
sessionFactory.setConfigLocation(new ClassPathResource(mybatisConfigPath));
sessionFactory.setPlugins(new Interceptor[]{new SchemaInterceptor()});
return sessionFactory.getObject();
}
注入【 3?? mapper.xml】这里使用${schemaName}获取配置的schema值:
<insert id="insertFileData" parameterType="map">
insert into ${schemaName}${target_table}( ${table_field} ) VALUES ( ${field_value} )
</insert>
总结
首先要注意的是,这里用的不是SpringMVC里的拦截器,而是mybatis的拦截器,拦截器是在执行mapper文件内的SQL前触发的,此时,如果你传递了schema参数,拦截器就不会覆盖schema的值,如果没有配置,则使用配置的默认值。
|