Spring Boot + JPA + Hibernate不同的表名前缀 [英] Spring Boot + JPA + Hibernate different table name prefix
问题描述
我正在开发一个多租户的应用程序(具有旧的数据库结构),我有一个共同的用户表和一组基于访问权限的表。
I am working on a multi-tenanted application (with old database structure) where I have a common user table and set of tables based on the access permission.
例如,如果用户可以使用不同公司C1和C2的发票,则数据库包含名称为C1_invoice和C2_invoice的表。
For example if the user can work with invoice of different companies C1 and C2, the database contains a tables with name C1_invoice and C2_invoice.
I能够使用 org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
为一家公司添加前缀所以我可以访问 C1_invoice 表。但是如何动态选择前缀C1或C2?
So I can access C1_invoice table. But how can I choose the prefix C1 or C2 dynamically?
推荐答案
您可以使用这种方法。
它基本上是通过提供自定义 MultiTenantConnectionProvider
在Spring Data中使用hibernate的多租户功能。连接提供程序从数据源映射中读取连接详细信息。您可以为每个数据源中的 hibernate.physical_naming_strategy
提供不同的值。我不确定是否有办法将每个数据源的前缀指定为属性。您最终可能会为每个租户提供 PhysicalNamingStrategy
的单独子类。可能很可怕。
It is basically using hibernate's multitenancy features in Spring Data by providing a custom MultiTenantConnectionProvider
. The connection provider reads connection details from a map of data sources. You could provide a different value for the hibernate.physical_naming_strategy
in each of the data sources. I'm not sure if there's a way to specify the prefix for each data source as a property, though. You could end up with a separate subclass of the PhysicalNamingStrategy
for each tenant. Could be gruesome.
您使用的数据库是什么?或者,您可以通过为每个租户提供一个架构来解决问题,并使用未加前缀的名称对默认架构中的表进行别名,这些内容类似于:
What DB are you using? Alternatively, you could resolve the issue by providing a schema per each tenant, and aliasing their tables from the default schema using unprefixed names, something along the lines of:
CREATE SYNONYM C1.INVOICE FOR DEFAULT.C1_INVOICE;
这样,您可以使用Hibernate的标准 MultitenancyStrategy.SCHEMA
策略。
This way, you could use Hibernate's standard MultitenancyStrategy.SCHEMA
strategy.
这篇关于Spring Boot + JPA + Hibernate不同的表名前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!