实现步骤:

1.引入mybatis-puls依赖

2.创建一个多租户拦截类实现TenantLineHandler接口,并实现

getTenantId()、getTenantIdColumn()、ignoreTable(String tableName)方法。

3.MybatisPlusInterceptor加入多租户拦截。

配置代码如下:

1.引入mybatis-puls依赖

<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3</version>
</dependency>

<!--多租户插件-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.5.3</version>
 </dependency>

2.创建一个多租户拦截类实现TenantLineHandler接口,并实现getTenantId()、getTenantIdColumn()、ignoreTable(String tableName)方法。

package com.lyz.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.lyz.utils.UserHoldUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

public class TenantIdInterceptor implements TenantLineHandler {


    @Override
    public Expression getTenantId() {
        // 这里返回当前登录用户的ID作为租户ID
        // 你需要根据你的认证/授权逻辑来获取用户ID
        Integer userId = UserHoldUtil.getUser().getId();// 获取当前登录用户的ID;
        return new LongValue(userId);
    }

    @Override
    public String getTenantIdColumn() {
        return "user_id"; // 数据库表中的租户ID列名
    }

    @Override
    public boolean ignoreTable(String tableName) {
        // 可以根据需要指定不应用租户隔离的表

        return "user".equals(tableName);
    }
}

3.MybatisPlusInterceptor加入多租户拦截。

package com.lyz.config;

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 org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false
     * 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 多租户插件
        TenantLineHandler tenantLineHandler = new TenantIdInterceptor();
        TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor(tenantLineHandler);
        interceptor.addInnerInterceptor(tenantLineInnerInterceptor);
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }




}

最后,点个赞在走吧!

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐