问题描述
您需要在多租户中使用MyBatis spring的一些帮助应用程序...
Hi needed some help in using MyBatis spring in a multi tenantapplication ...
有可能吗?特别是因为我不知道如何可以使用sqlSessionFactory来配置"MapperScannerConfigurer"运行.
Is it possible ? Especially since i do not see how"MapperScannerConfigurer" can be configured with sqlSessionFactory atrun time.
推荐答案
这是使用插件(也称为拦截器)切换模式"或目录"的另一种方法.
Here is another approach using a plugin (a.k.a. interceptor) to switch 'schema' or 'catalog'.
根据您使用的数据库,每个租户都有自己的数据库或架构.一些例子:
Depending on the database you use, each tenant has its own database or schema.A few examples:
- MySQL:每个租户都有自己的数据库",并且插件应调用
setCatalog
. - Oracle:每个租户都有其自己的模式",并且插件应调用
setSchema
. - SQL Server:每个租户都有自己的数据库",并且插件应调用
setCatalog
.
假设您通过ThreadLocal传递了租户ID,这是一个示例插件实现.
Assuming you pass the tenant ID via ThreadLocal, here is an example plugin implementation.
import java.sql.Connection;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
@Intercepts(
@Signature(
type = StatementHandler.class,
method = "prepare",
args = { Connection.class, Integer.class }))
public class MultiTenantInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
Connection con = (Connection) args[0];
con.setSchema(TenantIdHolder.getTenantId());
// con.setCatalog(TenantIdHolder.getTenantId());
return invocation.proceed();
}
}
TenantIdHolder
只是一个 ThreadLocal
持有人.
public class TenantIdHolder {
private static ThreadLocal<String> value = new ThreadLocal<>();
public static void setTenantId(String tenantId) {
value.set(tenantId);
}
public static String getTenantId() {
return value.get();
}
}
这是使用HSQLDB的演示.
Here is a demo using HSQLDB.
这篇关于MyBatis Spring在多租户应用程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!