标题党了;哈哈!!!
1.多租户插件
我们来看mybatis-Plus 提供的多租户插件还是很方便的: 多租户插件 | MyBatis-Plus
官方的例子其实已经很清晰,来看下我们实战中的例子;
首先是属性配置类:
import java.util.List;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 白名单配置
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "tenant")
public class TenantProperties {
/**
* 是否开启租户模式
*/
private Boolean enable;
/**
* 多租户字段名称
*/
private String column;
/**
* 需要排除的多租户的表
*/
private List<String> exclusionTable;
}
接下来是bean配置类
package com.caicongyang.hc.conf;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Objects;
@Configuration
public class MybatisPlusConfiguration {
@Autowired
TenantProperties tenantProperties;
@Bean
public Interceptor paginationInnerInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
if (tenantProperties.getEnable()) {
interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
@Override
public Expression getTenantId() {
String merchantCode = SystemContext.getUserInfo().getMerchantCode();
if (Objects.isNull(merchantCode)) {
return new StringValue("-1");
} else {
return new StringValue(SystemContext.getUserInfo().getMerchantCode());
}
}
// 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
@Override
public boolean ignoreTable(String tableName) {
return tenantProperties.getExclusionTable().stream().anyMatch(
(t) -> t.equalsIgnoreCase(tableName));
}
/**
* 获取多租户的字段名
* @return String
*/
@Override
public String getTenantIdColumn() {
return tenantProperties.getColumn();
}
}));
}
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
是不是很简单;基于管理平台这类的需求,如何忽略多租户呢; 我的建议是新建不同的mapper对象
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.caicongyang.hc.entity.Use