Java 如何对同一存储库使用多个数据源类型?
我创建了一个多租户逻辑,并将租户编号存储在Java 如何对同一存储库使用多个数据源类型?,java,hibernate,jpa,spring-boot,Java,Hibernate,Jpa,Spring Boot,我创建了一个多租户逻辑,并将租户编号存储在ThreadLocal中。当数据库属于同一类型(方言)时,一切都很好。在spring引导初始化期间,JPA存储库使用第一个(也是默认的)数据源进行初始化(其SQL查询) 然而,当我配置了例如Oracle和Postgres数据库时,spring boot仍然尝试使用第一个租户数据源的方言进行查询,这是一个相当大的问题,因为数据库类型的方言不同 这将创建租户类型的数据源。如果承租人还不知道(在启动过程中),则需要承租人-1 @Bean public Data
ThreadLocal
中。当数据库属于同一类型(方言)时,一切都很好。在spring引导初始化期间,JPA存储库使用第一个(也是默认的)数据源进行初始化(其SQL查询)
然而,当我配置了例如Oracle和Postgres数据库时,spring boot仍然尝试使用第一个租户数据源的方言进行查询,这是一个相当大的问题,因为数据库类型的方言不同
这将创建租户类型的数据源。如果承租人还不知道(在启动过程中),则需要承租人-1
@Bean
public DataSource dataSource() throws SQLException {
String tenant1 = "tenant-1";
String tenant2 = "tenant-2";
CustomRoutingDataSource customRoutingDataSource = new CustomRoutingDataSource();
final DataSource tenant1DataSource = createDataSourceForTenant(tenant1);
final DataSource tenant2DataSource = createDataSourceForTenant(tenant2);
HashMap<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(tenant1.toUpperCase(), tenant1DataSource);
targetDataSources.put(tenant2.toUpperCase(), tenant2DataSource);
customRoutingDataSource.setTargetDataSources(targetDataSources);
return customRoutingDataSource;
}
自定义数据库路由。当租户不可用时(在启动期间),getTenant返回默认值(1)
现在,如果我的默认租户=1,SpringBoot将在启动时初始化,并为实体创建特定于PostgreSQL的查询。如果我作为租户2(Oracle方言)在运行时访问它,我将获得:
java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended
正如Spring一样,JPA已经用PostgreSQL方言初始化了JPA存储库。因此,可能性是:
1)每个租户有多个EntityManager-由于租户是动态管理的,所以这不是很舒服2)hibernate中的多租户支持-事实上,我无法实现这一点,因为jadira框架在多租户支持方面存在一些问题,而且在2周之前仍未修复并等待
3)??刚发布的Jadira 5.0.0.GA中有一些变化,可以与多租户部署共存。免责声明:我维护Jadira
public class CustomRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return "TENANT-"+TenantThreadLocal.getTenant();
}
}
java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended