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

开始使用

simplest详细文档

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

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

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

配置

属性文件

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

自定义租户数据

java 复制代码
/**
 * @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

java 复制代码
@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 如下:

sql 复制代码
DELETE FROM tb_article where id = ? and tenant_id = ?
相关推荐
woniu_maggie6 分钟前
SAP FICO 分割评估_sap凭证分割配置
后端
mu_guang_22 分钟前
计算机体系结构2-内存一致性
java·后端·spring·计算机体系结构
小旭952723 分钟前
SpringBoot + 七牛云 + Quartz:图片存储与定时清理
java·spring boot·后端·mybatis
小码哥_常33 分钟前
揭秘!Spring Cloud Gateway为何独宠WebFlux
后端
世人万千丶36 分钟前
开源鸿蒙跨平台Flutter开发:儿童数理认知与神经塑性演化引擎_突触发生与工作记忆测绘架构
学习·flutter·华为·开源·harmonyos
darkb1rd41 分钟前
career-ops:Go 语言驱动 AI 求职系统实战指南
开源·github·好物分享
杰克尼1 小时前
springCloud(day09-Elasticsearch02)
java·后端·spring·spring cloud
@atweiwei1 小时前
用 Rust 构建 LLM 应用的高性能框架
开发语言·后端·ai·rust·langchain·llm
han_hanker1 小时前
springboot 不推荐使用@Autowired怎么处理
java·spring boot·后端
AscendKing1 小时前
一款开源、本地部署的 SSL 证书自动化管理工具Certimate介绍 部署教程
开源·自动化·ssl