I am using Spring Java Based configuration for configure multiple database with Spring Data.
In the configuration file, i am creating two data source
for MySQ
I had the same problem and after a lot of headache I stumbled upon this doc that made me feel really dumb :(
All you need is @Primary on one of your DataSources and Spring-Boot won't get confused anymore... Here is one of my configurations... The rest are pretty much identical, pointing to other DBs and with no @Primary on them...
@Configuration
@EnableTransactionManagement
@EntityScan(basePackages = {"somepackage.entities"})
@EnableJpaRepositories(entityManagerFactoryRef = "emfDB1", transactionManagerRef = "tmDB1", basePackages = {"somepackage.repositories"})
class PersistenceDB1 {
@Bean
@Primary
DataSource dsDB1() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl("jdbc:mysql://someserver:3306/proativo");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
return dataSource;
}
@Bean
@Primary
LocalContainerEntityManagerFactoryBean emfDB1() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dsDB1());
entityManagerFactoryBean.setJpaVendorAdapter(new EclipseLinkJpaVendorAdapter());
entityManagerFactoryBean.setPersistenceXmlLocation("classpath:META-INF/DB1-persistence.xml");
Properties jpaProperties = new Properties();
jpaProperties.put("eclipselink.weaving", "false");
jpaProperties.put("eclipselink.logging.level", "SEVERE"); // SEVERE / FINEST
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
@Bean
@Primary
JpaTransactionManager tmDB1() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emfDB1().getNativeEntityManagerFactory());
return transactionManager;
}
}
Edit: Forgot to mention: Probably due to the way my configuration classes are done, the method of excluding some classes on @EnableAutoConfiguration didn't work for me...
I had the same problem and found this old post that explained it:
http://xantorohara.blogspot.ch/2013/11/spring-boot-jdbc-with-multiple.html
It looks like if you need multiple data sources, the Spring Boot magic runs out, and you have to take over the configuration manually.
In my case, I had to modify the EnableAutoConfiguration to take over the data source and transaction manager configuration myself:
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,DataSourceTransactionManagerAutoConfiguration.class})
It looks like the Spring Boot magic ran out at the point I had to use multiple data sources...
I my case, the configuration was on a xml file, so I only have to add the primary="true" to the bean tag of one of the defined datasources.