How do you connect to multiple databases in a Spring Boot application?

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

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.

@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.

Last updated: 11 November 2026

Previous question: What changes are needed to switch from Logback to Log4j2 in Spring Boot?

Next question: How does Spring Boot handle database migrations?

More Spring Boot - Level IV (Advanced) interview questions

All Spring Boot - Level IV (Advanced) questions