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

Connecting multiple databases in a Spring Boot application requires explicitly defining separate DataSource, EntityManagerFactory, and TransactionManager beans for each database, since Spring Boot's auto-configuration only handles a single default data source.

Key Points: • Each database gets its own @Configuration class defining a DataSource, EntityManagerFactory, and TransactionManager, scoped to a distinct base package for its entities and repositories. • @Primary marks one DataSource (and its related beans) as the default candidate, resolving ambiguity for unqualified injections. • @Qualifier is used at injection points that need the non-primary data source explicitly. • Repository interfaces are split by package so @EnableJpaRepositories can point each repository group at the correct EntityManagerFactory. • Cross-database transactions aren't atomic under local transaction managers; a distributed transaction manager like JTA is needed if true two-phase commit is required.

Example: An application reading from a legacy reporting database and writing to a primary transactional database defines two full sets of DataSource/EntityManagerFactory/TransactionManager beans, with @Primary on the transactional database's beans and @Qualifier used wherever the reporting database is accessed.

Code Example:

@Bean
@Primary
@ConfigurationProperties("app.datasource.primary")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties("app.datasource.reporting")
public DataSource reportingDataSource() {
    return DataSourceBuilder.create().build();
}

Interview Tip: A concise interview answer is:

"I define a separate DataSource, EntityManagerFactory, and TransactionManager for each database in its own configuration class, mark one set as @Primary, and use @Qualifier wherever I need to inject the other explicitly. Repositories are split into separate packages so each one is wired to the correct EntityManagerFactory."