在运行时根据登录用户和共享架构更改数据库架构

时间:2021-05-12 08:32:12

标签: java spring-boot hibernate spring-data-jpa

我将 Springboot 2 与 hibernate 和 spring 数据 JPA 一起使用。

之前我们使用的是 JDBC 模板,我们根据登录用户将模式名称添加到 SQL 查询中。喜欢 -

String sql = "Select * from " + scheama + ".table"

现在我们需要在 hibernate 中提供类似的支持。

我在堆栈溢出方面发现了几个类似的问题,例如 -

我们有每个用户的架构,还有一些不依赖于登录用户的共享架构。 在上面的例子中,我可以为登录用户处理架构,但有没有办法同时处理用户架构和共享架构。

获取架构的代码示例 -

String sceama = this.companyService.getScheama(this.getUserCompany(request.getHeader("selectedCompany")));

2 个答案:

答案 0 :(得分:1)

您可以通过使用 Hibernate 配置多租户来做到这一点。见https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#multitenacy

答案 1 :(得分:0)

找到了两个解决方案,都解决了我的问题。

解决方案 1 - 创建了一个休眠拦截器并在 SQL 查询中添加动态模式。

https://dzone.com/articles/hibernate-dynamic-table-routin

public class HibernateInterceptor extends EmptyInterceptor {

    @Override
        public String onPrepareStatement(String sql) {
              String prepedStatement = super.onPrepareStatement(sql);
              prepedStatement = prepedStatement.replaceAll("secure.identitymanagement", "my_dynamic_goodness");
              return prepedStatement;
        }
    
    }

解决方案 2 - 配置了两种不同的架构 - 一种用于共享/通用架构,另一种用于特定于用户的架构。

此博客解释了“每个租户的数据库”和“每个租户的架构”。 https://callistaenterprise.se/blogg/teknik/2020/09/19/multi-tenancy-with-spring-boot-part1/