Hibernate中如何实现多租户?代码举例讲解

在Hibernate中,多租户(Multi-tenancy)表示同一套系统被多个租户(Tenant)独立使用,每个租户的数据相互隔离。主要有以下两种实现方式:

  1. 基于数据库的多租户:
  • 为每个租户创建独立的数据库或schema,租户的数据在不同的数据库/schema中隔离。
  • 租户与数据源(DataSource)的映射关系可以存储在服务器端,代码中根据租户ID查找对应的数据源进行数据访问。

例如:

DataSource getDataSource(Integer tenantId) {
    return dataSourceMap.get(tenantId);  // 从map中获取
}

Session session = sessionFactory.withOptions()  // 指定数据源的SessionFactory
                                .tenantIdentifier(tenantId) 
                                .dataSource(getDataSource(tenantId))  
                                .openSession();
  1. 基于表的多租户:
  • 所有租户的数据存储在同一数据库,通过引入tenant_id字段来区分不同的租户。
  • Hibernate可以通过@TenantId注解指定租户字段,会根据该字段过滤数据。

例如:

@Entity(tenantId = "tenant_id")
public class Customer {
    @Id 
    private int id;

    @TenantId  
    private String tenantId;   // 租户字段  

    ...
}
sessionFactory.getProperties().put("hibernate.multiTenancy", "SCHEMA");
Session session = sessionFactory.withOptions()  
                             .tenantIdentifier("tenant1")  // 指定租户
                             .openSession();