Multiple database connections in a Spring Boot app are set up by defining separate DataSource, EntityManagerFactory, and TransactionManager beans for each database, configured in distinct @Configuration classes.
Key Points: • Each database gets its own @Configuration class with @Bean methods for its DataSource, EntityManagerFactory, and TransactionManager. • @Primary marks one DataSource as the default when Spring needs to pick automatically. • @Qualifier is used on injection points in repositories/services to specify exactly which DataSource or EntityManagerFactory to use. • Repositories for each database are usually placed in separate packages, scanned via @EnableJpaRepositories(basePackages = ..., entityManagerFactoryRef = ...). • Connection pool settings (e.g. HikariCP) should be tuned independently for each database based on its expected load.
Example: An application that reads product data from a legacy Oracle database while writing orders to a newer PostgreSQL database defines two full sets of DataSource/EntityManagerFactory/TransactionManager beans, one per database, and wires each repository to the correct one with @Qualifier.
Code Example:
@Configuration
@EnableJpaRepositories(
basePackages = "com.example.orders.repo",
entityManagerFactoryRef = "ordersEntityManagerFactory",
transactionManagerRef = "ordersTransactionManager")
public class OrdersDbConfig {
@Primary
@Bean
public DataSource ordersDataSource() {
return DataSourceBuilder.create().url("jdbc:postgresql://.../orders").build();
}
}Interview Tip: A concise interview answer is:
"I create a separate @Configuration class per database, each defining its own DataSource, EntityManagerFactory, and TransactionManager beans, and use @EnableJpaRepositories to point each repository package at the right factory. @Qualifier disambiguates injection where Spring can't infer which bean to use."