#schema.sql
drop table if exists user;
create table user
(
id bigint(20) not null comment '主键',
provider_id bigint(20) not null comment '服务商id',
name varchar(30) null default null comment '姓名',
primary key (id)
);
#data.sql
insert into user (id, provider_id, name) values (1, 1, 'tony老师');
insert into user (id, provider_id, name) values (2, 1, 'william老师');
insert into user (id, provider_id, name) values (3, 2, '路人甲');
insert into user (id, provider_id, name) values (4, 2, '路人乙');
insert into user (id, provider_id, name) values (5, 2, '路人丙');
insert into user (id, provider_id, name) values (6, 2, '路人丁');
mybatisplus config
基础环境搭建完成,现在开始配置mybatisplus多租户相关的实现。
1) 核心配置:tenantsqlparser
@configuration
@mapperscan("com.wuwenze.mybatisplusmultitenancy.mapper")
public class mybatisplusconfig {
private static final string system_tenant_id = "provider_id";
private static final list<string> ignore_tenant_tables = lists.newarraylist("provider");
@autowired
private apicontext apicontext;
@bean
public paginationinterceptor paginationinterceptor() {
paginationinterceptor paginationinterceptor = new paginationinterceptor();
// sql解析处理拦截:增加租户处理回调。
tenantsqlparser tenantsqlparser = new tenantsqlparser()
.settenanthandler(new tenanthandler() {
@override
public expression gettenantid() {
// 从当前系统上下文中取出当前请求的服务商id,通过解析器注入到sql中。
long currentproviderid = apicontext.getcurrentproviderid();
if (null == currentproviderid) {
throw new runtimeexception("#1129 getcurrentproviderid error.");
}
return new longvalue(currentproviderid);
}
@override
public string gettenantidcolumn() {
return system_tenant_id;
}
@override
public boolean dotablefilter(string tablename) {
// 忽略掉一些表:如租户表(provider)本身不需要执行这样的处理。
return ignore_tenant_tables.stream().anymatch((e) -> e.equalsignorecase(tablename));
}
});
paginationinterceptor.setsqlparserlist(lists.newarraylist(tenantsqlparser));
return paginationinterceptor;
}
@bean(name = "performanceinterceptor")
public performanceinterceptor performanceinterceptor() {
return new performanceinterceptor();
}
}
2) apicontext
@component
public class apicontext {
private static final string key_current_provider_id = "key_current_provider_id";
private static final map<string, object> mcontext = maps.newconcurrentmap();
public void setcurrentproviderid(long providerid) {
mcontext.put(key_current_provider_id, providerid);
}
public long getcurrentproviderid() {
return (long) mcontext.get(key_current_provider_id);
}
}
3) entity、mapper
@data
@tostring
@accessors(chain = true)
public class user {
private long id;
private long providerid;
private string name;
}
public interface usermapper extends basemapper<user> {
}