tuqin
2026-10-29 0a3129cb06fcea6677245097715dcc6fa3de65e5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.ruoyi.common.handler;
 
 
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.ruoyi.common.config.IgnoreTableConfig;
import com.ruoyi.common.utils.SecurityUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
 
import java.util.Set;
 
@Component
public class CustomTenantLineHandler implements TenantLineHandler {
 
    /**
     * 临时跳过租户过滤的开关。
     *
     * 场景:匿名接口(设备回传)、全局配置表(如清洗规则)这类没有登录上下文的数据,
     * 不应该被自动加上 tenant_id 条件。用法:
     *   CustomTenantLineHandler.TEMP_IGNORE.set(Boolean.TRUE);
     *   try { ... } finally { CustomTenantLineHandler.TEMP_IGNORE.remove(); }
     */
    public static final ThreadLocal<Boolean> TEMP_IGNORE = new ThreadLocal<>();
 
    @Override
    public Expression getTenantId() {
        try {
            Long tenantId = SecurityUtils.getLoginUser().getTenantId();
            return new LongValue(tenantId);
        } catch (Exception e) {
            return null;
        }
    }
 
    @Override
    public boolean ignoreTable(String tableName) {
        // 临时跳过(匿名接口 / 全局配置表)
        if (Boolean.TRUE.equals(TEMP_IGNORE.get())) {
            return true;
        }
        // 指定不需要添加过滤条件的表
        Set<String> ignoreTables = IgnoreTableConfig.IGNORE_TABLES;
        return ignoreTables.contains(tableName);
    }
 
    @Override
    public String getTenantIdColumn() {
        // 指定租户 ID 字段名称,比如 "station_id"
        return "tenant_id";
    }
}