simplest-jpa v1.2.0如何优雅实现多租户

开始使用

simplest详细文档

simplest-jpa 使用多租户需要 2 个步骤:

  1. 在属性中配置对应租户表和列。
  2. 配置 TenantFactory 注入租户数据源

TenantFactory 是用于生产租户 ID 的,或者说是用于获取当前租户 ID 的。

配置

属性文件

jpa:
  properties:
    hibernate:
      session_factory:
        statement_inspector: cn.soboys.simplestjpa.interceptor.TenantInterceptor #配置指定租户拦截器
# 需进行租户解析的租户表
tenant:
  tables:
    - cms_category
  tenant-id-column: tenant_id
  enableTenant: true

自定义租户数据

/**
 * @author 公众号 程序员三时
 * @version 1.0
 * @date 2023/7/30 22:15
 * @webSite https://github.com/coder-amiao
 */
@Configuration
public class TenantConfig implements TenantFactory {
    
    

    @Override
    public String getTenantId() {
    
    
        return "8";
    }
}

::: tip
如果getTenantId()返回空或者null会自动过滤。
:::

忽略租户条件

在某些场景下,在增删改查等操作,我们可能需要忽略租户条件, 此时可以设置CustomTenant
withoutTenantCondition

@Test
void countByExample() {
    
    
    CustomTenant.withoutTenantCondition=true; //自定义不设置租户拦截
    Category category = new Category();
    category.setTitle("测试");
    long count = categoryService.count(Example.of(category));
    log.info("条件count{}", count);
}

示列

删除、修改和查询表在指定属性配置表中。都会带上租户的条件。

比如根据 ID 删除,那么执行的 SQL 如下:

DELETE FROM tb_article where id = ? and tenant_id = ?

猜你喜欢

转载自blog.csdn.net/u011738045/article/details/132109668