Hibernate 自动应用租户条件 (tenant_id) 的最佳实践
Hibernate 可以使用过滤器 (Filter) 来自动应用 tenant_id 的租户条件。过滤器是一种在 Session 级别上对数据进行过滤的机制,它可以动态地将一些条件加入到查询中,从而过滤掉不符合条件的数据。
首先,在实体类上添加一个 'tenant_id' 字段,表示租户的标识:
@Entity
@Table(name = "my_table")
@FilterDef(name = "tenantFilter", parameters = @ParamDef(name = "tenantId", type = "long"))
public class MyTable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "tenant_id")
private Long tenantId;
// other fields and methods
}
然后,在 Hibernate 配置文件中定义一个过滤器:
<hibernate-configuration>
<session-factory>
<!-- other configuration -->
<filter-def name="tenantFilter">
<filter-param name="tenantId" type="long"/>
</filter-def>
</session-factory>
</hibernate-configuration>
最后,在需要过滤数据的地方,通过 Session 的 enableFilter 方法启用过滤器,将 'tenant_id' 的值设置为当前租户的标识:
Session session = sessionFactory.getCurrentSession();
session.enableFilter("tenantFilter").setParameter("tenantId", currentTenantId);
List<MyTable> list = session.createQuery("from MyTable").list();
这样,查询 MyTable 实体时,Hibernate 会自动将租户条件加入到查询中,只返回符合当前租户标识的数据。
原文地址: https://www.cveoy.top/t/topic/oKJ5 著作权归作者所有。请勿转载和采集!