Using Spring Data JPA with multiple data sources

Using Spring Data JPA with multiple data sources means giving each database its own entities, repositories, entity manager factory, and transaction manager. This suits systems where orders, audit events, reporting records, or legacy data live in separate schemas or database engines.

The hard part is not opening two connections; it is preventing a secondary repository from silently using the primary one. Explicit bean names, disjoint entity packages, and qualified transaction managers make the data path unambiguous.

Build separate persistence units

Spring Boot’s default persistence setup assumes one persistence unit, so a multi-database application should define one configuration class per database. Repository scanning, entity scanning, the datasource, the entity manager factory, and the transaction manager must all point to the same logical store.

@Configuration
@EnableJpaRepositories(
    basePackages = "com.acme.order.repository",
    entityManagerFactoryRef = "orderEntityManagerFactory",
    transactionManagerRef = "orderTransactionManager")
@EntityScan("com.acme.order.entity")
class OrderJpaConfiguration {

    @Bean
    @Primary
    @ConfigurationProperties("app.datasource.order")
    DataSourceProperties orderDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Primary
    @ConfigurationProperties("app.datasource.order.configuration")
    HikariDataSource orderDataSource(
            @Qualifier("orderDataSourceProperties") DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder()
                .type(HikariDataSource.class)
                .build();
    }

    @Bean
    @Primary
    LocalContainerEntityManagerFactoryBean orderEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("orderDataSource") DataSource dataSource) {
        return builder.dataSource(dataSource)
                .packages("com.acme.order.entity")
                .build();
    }

    @Bean
    @Primary
    PlatformTransactionManager orderTransactionManager(
            @Qualifier("orderEntityManagerFactory") EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }
}

Create an equivalent audit configuration using distinct bean names and audit packages. Mark only the default set of beans as @Primary; this gives unqualified injections a deterministic target while qualified references remain explicit. The second configuration must not repeat the first configuration’s package names.

Keep entity mappings independent

Each @Entity belongs to exactly one persistence unit. For example, Order and Invoice may use the order database, while AuditEvent uses the audit database. If the same table must be queried through both stores, prefer a read-only DTO or native projection over duplicating a managed entity across both scans.

JPA relationships do not cross a datasource boundary. A lazy @ManyToOne from an order to a reporting record cannot join rows in another database or share a persistence context. Persist the related identifier, fetch it through the correct repository, or replicate the small piece of data needed for the local transaction.

Run Flyway or Liquibase against each connection separately, with its own migration history. This keeps schema changes aligned with the entities that the corresponding entity manager factory can see.

Control transactions explicitly

A service that writes to the audit store must name that store’s transaction manager. Without a qualifier, Spring uses the primary transaction manager, and the repository call can be enlisted in the wrong transaction.

@Service
class AuditService {

    @Transactional(transactionManager = "auditTransactionManager")
    public void save(AuditEvent event) {
        auditRepository.save(event);
    }
}

Use read-only transactions for reporting queries, and keep cross-store workflows explicit. A process that commits an order in one database and then writes its audit event in another needs compensation, retry handling, or an outbox; two independent commits cannot become atomic merely by annotating both methods.

Also avoid injecting a generic EntityManager into shared services. Inject the qualified entity manager factory or repository belonging to the required database instead.

Apply a production configuration checklist

Before deployment, check the wiring and operational controls as separate concerns.

Persistence-unit wiring

Operational safeguards

Run these checks in CI with isolated schemas, then repeat them against a production-like environment. A configuration test that only starts the application is insufficient because bean creation can succeed while repository routing remains wrong.

Test each data source in isolation

Start with integration tests that invoke one repository from each database and assert against the correct schema. Also capture the active datasource or persistence unit in diagnostic logs; a repository call that exposes an unexpected table usually reveals a missing qualifier or overlapping package.

Common issues include an auto-configured default datasource winning injection, lazy loading after a transaction closes, and schema migrations running on the wrong connection. Reject ambiguous beans, fetch required data inside the transaction, and bind each migration runner to an explicit datasource.

Separate modules should not share persistence units merely because they share a deployment. JavaWhizz’s online casino game strategies guide could sit behind a separate content service, with catalogue data in its own store, without entering the order or audit persistence units.

For Australian SaaS teams, confirm that AUD amounts and GST reporting data stay in the intended reporting database, and verify resilience across Sydney and Melbourne. Where policy calls for Australian data residency, keep databases and backups in approved Australian regions rather than assuming a nearby region is sufficient.