2017-01-02 80 views
0

我有一個單一的SQL服務器數據庫下的多個數據庫。 from application.properties文件。我已經配置爲在springboot中默認模式。 現在我想chage到另一個數據庫具有相同的URL,usrname,pawd。春季啓動多個數據庫配置與微軟的SQL服務器

我該如何改變這一點?當我給註釋了類

@table (name = db2.dbo.tname) 

它拋出的錯誤說法,

無法將這個dboject數據庫1

這裏地圖是我的配置:

spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=testdb;integratedSecurity=false; 

spring.datasource.username=sa 
spring.datasource.password=myPassword 
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerConnection 
spring.datasource.initialize=true 

我的應用程序使用我在應用程序屬性上給出的默認數據庫。但我必須連接到另一個數據庫。 我該如何解決這個問題?

回答

0

你不能使用普通的彈簧屬性來做到這一點。這裏是你如何可以連接到兩個數據庫(或更多,如果你需要)一個例子:

首先,你必須禁用拿起只是一個數據庫的自動配置:

@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class}) 

而現在你只需要提供自己的配置JPA和數據源:

@Configuration 
@EnableJpaRepositories(entityManagerFactoryRef = "ds1EntityManagerFactory", 
     transactionManagerRef = "ds1TransactionManager", 
     basePackageClasses = Ds1Repository.class) 
public class DataSource1Config { 

    @Bean 
    PlatformTransactionManager ds1TransactionManager() { 
     return new JpaTransactionManager(tfccgEntityManagerFactory().getObject()); 
    } 

    @Bean 
    LocalContainerEntityManagerFactoryBean ds1EntityManagerFactory() { 

     HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); 

     LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); 

     factoryBean.setDataSource(ds1()); 
     factoryBean.setJpaVendorAdapter(vendorAdapter); 
     factoryBean.setPackagesToScan(Ds1Entity.class.getPackage().getName()); 
     factoryBean.getJpaPropertyMap().put("hibernate.dialect", dialect); 
     factoryBean.getJpaPropertyMap().put("hibernate.show_sql", showSQL); 
     factoryBean.getJpaPropertyMap().put("hibernate.globally_quoted_identifiers", quoteIdentifiers); 

     return factoryBean; 
    } 

    @Bean 
    DataSource ds1() { 
     BasicDataSource dataSource = new BasicDataSource(); 
     dataSource.setUrl(url); 
     dataSource.setDriverClassName(driverClass); 
     dataSource.setUsername(username); 
     dataSource.setPassword(password); 
     dataSource.setTestOnBorrow(testOnBorrow); 
     dataSource.setMaxTotal(maxTotal); 
     dataSource.setInitialSize(initialSize); 
     dataSource.setMaxIdle(maxIdle); 
     return dataSource; 
    } 
} 

你可以有一個ds2數據源這個類的一個副本上,您將有第二組transactionManagerentityManagerFactorydatasource和O n您將爲不同的軟件包啓用JPA Repositories和Entity掃描併爲不同名稱的Bean命名。

然後,如果你需要在一個方法的事務隔離,你必須提供transactionManager名字,因爲你有2個:

@Transactional(transactionManager = "ds1TransactionManager")

+0

在數據源URL – Ulises