Skip to content
广告❤️成为赞助商

Multi-Tenant Handler

TenantHandler is a plugin provided by Mongo-Plus for implementing multi-tenant data isolation. With this plugin, each tenant can only access their own data, ensuring secure data segregation.

TenantHandler

  • Multi-tenant handler interface
  • BsonValue getTenantId(): Get the tenant ID
  • String getTenantIdColumn(): Get the tenant field, default is 'tenant_id'
  • boolean ignoreCollection(collectionName): Determine whether to ignore tenant for a given collection
  • boolean ignoreDatabase(database): Determine whether to ignore tenant for a given database
  • boolean ignoreDataSource(dataSource): Determine whether to ignore tenant for a given data source
  • boolean ignoreInsert(columns, tenantIdColumn): Ignore inserting tenant field logic

@IgnoreTenant

  • Annotation to ignore tenant injection, can be placed on methods

Example

Implement the TenantHandler interface, create a tenant handler, and register it as a Bean. In this example, we assume each tenant has a unique tenantId, which is retrieved from the request header.

java
@Component
public class CustomTenantHandler implements TenantHandler {

    @Override
    public BsonValue getTenantId() {
        // Assume there is a tenant context to get the current user's tenant
        Long tenantId = TenantContextHolder.getCurrentTenantId();
        // Return the tenant ID expression, BsonInt64 is the class representing bigint in JSQLParser
        return new BsonInt64(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        return "tenant_id";
    }

    @Override
    public boolean ignoreCollection(String collectionName) {
        // Return whether to ignore this collection based on requirements
        return false;
    }

}

Programmatic Tenant Ignoring

Using the TenantManager class, you can ignore tenants programmatically, suitable for fine-grained tenant ignoring:

java
TenantManager.withoutTenant(() -> {
    baseMapper.list();
});