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 = ?
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值