Для решения данной задачи используется класс AbstractRoutingDataSource
В свой проект добавила три класса:
Первый:
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class MultitenantDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return TenantContext.getCurrentTenant();
}
}
Второй:
public class TenantContext {
private static ThreadLocal<Object> currentTenant = ThreadLocal.withInitial(() -> "TenantTwo") ;
public static void setCurrentTenant(Object tenant) {
currentTenant.set(tenant);
}
public static Object getCurrentTenant() {
return currentTenant.get();
}
}
Третий содержит все настройки подключения к БД:
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.context.annotation.Configuration;
import ebi.zmap.MultitenantDataSource; // здесь импортируется ваш класс из первого файла
import java.io.*;
import java.nio.file.Paths;
import java.util.*;
import java.util.Properties;
@Configuration
public class MultitenantConfiguration {
@Autowired
private DataSourceProperties properties;
/**
* Defines the data source for the application
* @return
*/
@Bean
@ConfigurationProperties(
prefix = "spring.datasource"
)
public DataSource dataSource() {
AbstractRoutingDataSource dataSource = new MultitenantDataSource();
Map<Object,Object> targetDataSources = new HashMap<>();
targetDataSources.put("TenantOne", tenantOne());
targetDataSources.put("TenantTwo", tenantTwo());
targetDataSources.put(null, tenantOne());
dataSource.setTargetDataSources(targetDataSources);
dataSource.afterPropertiesSet();
return dataSource;
}
public DataSource tenantOne() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setInitializationFailTimeout(0);
dataSource.setMaximumPoolSize(5);
dataSource.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
dataSource.addDataSourceProperty("url", "jdbc:mysql://127.0.0.1:3306/annotrack");
dataSource.addDataSourceProperty("user", "root");
dataSource.addDataSourceProperty("password", "");
return dataSource;
}
public DataSource tenantTwo() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setInitializationFailTimeout(0);
dataSource.setMaximumPoolSize(5);
dataSource.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
dataSource.addDataSourceProperty("url", "jdbc:mysql://127.0.0.1:3306/annotrackm");
dataSource.addDataSourceProperty("user", "root");
dataSource.addDataSourceProperty("password", "");
return dataSource;
}
/**
* Creates the default data source for the application
* @return
*/
private DataSource defaultDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setInitializationFailTimeout(0);
dataSource.setMaximumPoolSize(5);
dataSource.setDataSourceClassName("com.mysql.cj.jdbc.Driver");
dataSource.addDataSourceProperty("url", "jdbc:mysql://193.62.52.185:3306/annotrack");
dataSource.addDataSourceProperty("user", "admin");
dataSource.addDataSourceProperty("password", "interestingtimes");
return dataSource;
}
}
В итоге в контроллер добавляем одну строку установки нужной нам бд (она может приходить в запросе):
TenantContext.setCurrentTenant(db);
@EnableJpaRepositories
, завязанных на два разныхentityManagerFactory
.