Video in progress

Strong Middle 🌱 Spring

How do you connect to two different databases from one Spring Boot application?

Boot auto-config sets up just one DataSource. For the second one you write the DataSource, EntityManagerFactory and TransactionManager by hand, split the repositories by package, and mark one of them @Primary.

📖 Answer

app:
  datasource:
    main:
      url: jdbc:postgresql://db1/shop
      username: shop
    reporting:
      url: jdbc:postgresql://db2/reports
      username: report
@Configuration
@EnableJpaRepositories(basePackages = "uz.shop.reporting.repo",
        entityManagerFactoryRef = "reportingEmf",
        transactionManagerRef = "reportingTx")
class ReportingDbConfig {

    @Bean @ConfigurationProperties("app.datasource.reporting")
    DataSourceProperties reportingProps() { return new DataSourceProperties(); }

    @Bean
    DataSource reportingDataSource() {
        return reportingProps().initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

    @Bean
    LocalContainerEntityManagerFactoryBean reportingEmf(EntityManagerFactoryBuilder b) {
        return b.dataSource(reportingDataSource()).packages("uz.shop.reporting.model").build();
    }

    @Bean
    PlatformTransactionManager reportingTx(@Qualifier("reportingEmf") EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }
}

The main database gets a class just like this one, only with @Primary.

Where people trip up:

  • By default @Transactional picks the @Primary transaction manager. For the second database write @Transactional("reportingTx"), otherwise the writes go through without a transaction.
  • There's no single transaction across two databases. If you need to write to both atomically, rethink the design (outbox, compensation). XA/JTA exists too, but it's complex and slow.
  • If you only read from the second database, JdbcTemplate/JdbcClient comes out much simpler than JPA.