Spring Boot with more than one database

Spring Boot configures one DataSource, one EntityManagerFactory and one transaction manager on its own. A second database means taking over part of that work, and a single wrong bean definition can silently switch the whole application to the wrong database. This page runs each setup, from a second JdbcTemplate to read replicas and per-tenant routing, and the traps between them.

Contents

Why a second database needs care

Spring Boot's database auto-configuration builds a chain of beans: a DataSource from spring.datasource.*, then a JdbcTemplate, an EntityManagerFactory and a transaction manager on top of it. Each link is created only if you have not defined a bean of that type yourself. That rule is what makes customizing easy, and it is also what goes wrong with a second database: defining your own DataSource bean makes the auto-configured one disappear.

Applications use more than one database for different reasons, and each reason has its own setup:

Multiple-database setups
SetupWhat it isBest for
A second DataSource with defaultCandidate = false (Spring Framework 6.2, Spring Boot 3.4)An extra pool, injected by qualifier, next to the auto-configured oneReporting, legacy or reference databases used with JDBC
A second EntityManagerFactorySeparate JPA persistence units, each with its entities, repositories and transaction managerTwo databases that both hold entities
AbstractRoutingDataSourceOne DataSource bean that picks a target per call from a lookup keyRead replicas, one database per tenant
LazyConnectionDataSourceProxy with a read-only target (Spring Framework 6.1.2)Read-only transactions use a second poolRead replicas, without writing a router

The examples run Spring Boot 4.1 and Spring Framework 7.0 against several in-memory H2 databases. Each database is named after its role, so SELECT DATABASE() shows which one a call reached. The routing examples use plain Spring without Spring Boot, because routing works the same in both.

A second DataSource next to the auto-configured one

An orders database is the application's main database, and a reporting database is used only by a few queries. The reporting pool is defined with Spring Boot's own DataSourceProperties, so it takes the same kinds of settings as spring.datasource.*, under its own prefix:

Java
package multi.jdbc;

import com.zaxxer.hikari.HikariDataSource;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.autoconfigure.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

@SpringBootApplication
public class TwoDataSources {

    @Bean(defaultCandidate = false)
    @Qualifier("reporting")
    @ConfigurationProperties("app.reporting.datasource")
    DataSourceProperties reportingProperties() {
        return new DataSourceProperties();
    }

    @Bean(defaultCandidate = false)
    @Qualifier("reporting")
    @ConfigurationProperties("app.reporting.datasource.hikari")
    HikariDataSource reportingDataSource(
            @Qualifier("reporting") DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

    @Bean(defaultCandidate = false)
    @Qualifier("reporting")
    JdbcTemplate reportingJdbc(@Qualifier("reporting") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(TwoDataSources.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.datasource.url", "jdbc:h2:mem:orders",
                "spring.datasource.hikari.pool-name", "orders-pool",
                "app.reporting.datasource.url", "jdbc:h2:mem:reporting",
                "app.reporting.datasource.hikari.pool-name", "reporting-pool",
                "app.reporting.datasource.hikari.maximum-pool-size", "2"));
        try (var context = app.run(args)) {
            System.out.println("DataSource beans: "
                    + String.join(", ", context.getBeanNamesForType(DataSource.class)));
            DataSource main = context.getBean(DataSource.class);
            HikariDataSource reporting = context.getBean("reportingDataSource",
                    HikariDataSource.class);
            System.out.println("Injected without qualifier: "
                    + ((HikariDataSource) main).getPoolName());
            System.out.println("reporting pool: " + reporting.getPoolName()
                    + ", max size " + reporting.getMaximumPoolSize()
                    + ", url " + reporting.getJdbcUrl());

            JdbcTemplate orders = context.getBean(JdbcTemplate.class);
            JdbcTemplate reports = context.getBean("reportingJdbc", JdbcTemplate.class);
            System.out.println("Unqualified JdbcTemplate talks to: "
                    + orders.queryForObject("SELECT DATABASE()", String.class));
            System.out.println("Qualified JdbcTemplate talks to  : "
                    + reports.queryForObject("SELECT DATABASE()", String.class));
        }
    }
}
Output
DataSource beans: reportingDataSource, dataSource
Injected without qualifier: orders-pool
reporting pool: reporting-pool, max size 2, url jdbc:h2:mem:reporting
Unqualified JdbcTemplate talks to: ORDERS
Qualified JdbcTemplate talks to  : REPORTING
  • Two DataSource beans exist: dataSource, created by Spring Boot from spring.datasource.*, and reportingDataSource.
  • Injecting a DataSource without a qualifier gave orders-pool. @Bean(defaultCandidate = false) means the reporting bean is used only where it is asked for by qualifier, so it neither competes for unqualified injection points nor counts as "the user defined a DataSource".
  • The reporting pool took its URL from app.reporting.datasource.url and its Hikari settings, such as maximum-pool-size=2, from app.reporting.datasource.hikari.*. DataSourceProperties translates url into Hikari's jdbcUrl.
  • The unqualified JdbcTemplate reached ORDERS and the qualified one REPORTING. The reporting JdbcTemplate is also defaultCandidate = false; the next section shows why that matters.

In Spring Boot 3 code before 3.4, you will see the older pattern instead: both DataSource beans defined by hand, with @Primary on one of them. It works, but it means rebuilding the main data source yourself.

The back-off trap

Auto-configured beans are created with "only if missing" conditions. A bean of the same type that you add for the second database therefore replaces, rather than joins, the auto-configured one. This program starts two applications, each with one plain @Bean too many:

Java
package multi.backoff;

import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

public class BackOffTrap {

    @Configuration
    @EnableAutoConfiguration
    static class PlainDataSourceBean {
        @Bean
        DataSource reportingDataSource() {
            return DataSourceBuilder.create().url("jdbc:h2:mem:reporting").build();
        }
    }

    @Configuration
    @EnableAutoConfiguration
    static class PlainJdbcTemplateBean {
        @Bean(defaultCandidate = false)
        @Qualifier("reporting")
        DataSource reportingDataSource() {
            return DataSourceBuilder.create().url("jdbc:h2:mem:reporting").build();
        }

        @Bean
        JdbcTemplate reportingJdbc(@Qualifier("reporting") DataSource dataSource) {
            return new JdbcTemplate(dataSource);
        }
    }

    static void show(Class<?> config) {
        SpringApplication app = new SpringApplication(config);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.datasource.url", "jdbc:h2:mem:orders"));
        try (var context = app.run()) {
            System.out.println(config.getSimpleName());
            System.out.println("  DataSource beans  : "
                    + String.join(", ", context.getBeanNamesForType(DataSource.class)));
            System.out.println("  JdbcTemplate beans: "
                    + String.join(", ", context.getBeanNamesForType(JdbcTemplate.class)));
            System.out.println("  injected JdbcTemplate uses database "
                    + context.getBean(JdbcTemplate.class)
                            .queryForObject("SELECT DATABASE()", String.class));
        }
    }

    public static void main(String[] args) {
        show(PlainDataSourceBean.class);
        show(PlainJdbcTemplateBean.class);
    }
}
Output
PlainDataSourceBean
  DataSource beans  : reportingDataSource
  JdbcTemplate beans: jdbcTemplate
  injected JdbcTemplate uses database REPORTING
PlainJdbcTemplateBean
  DataSource beans  : reportingDataSource, dataSource
  JdbcTemplate beans: reportingJdbc
  injected JdbcTemplate uses database REPORTING
  • A plain DataSource bean: spring.datasource.url pointed at ORDERS, but the auto-configured dataSource was never created. The only DataSource is reportingDataSource, and Spring Boot built its JdbcTemplate (and JPA, had there been entities) on top of it. Everything silently used REPORTING.
  • A plain JdbcTemplate bean: this time the DataSource was marked defaultCandidate = false, and both pools exist. But the auto-configured jdbcTemplate backed off because reportingJdbc exists, so injecting a JdbcTemplate again gave the reporting one.

Neither case fails at startup, which is what makes it dangerous. Mark every extra bean for the second database, whether DataSource, JdbcTemplate, EntityManagerFactory or transaction manager, with defaultCandidate = false and a qualifier. The startup condition report (--debug) lists each auto-configuration that backed off and why.

Two databases with JPA

With entities in both databases, each database needs its own EntityManagerFactory, transaction manager and repository scan. Customers live in the main CRM database and invoices in a billing database, each entity in its own package so that each factory scans only its own:

Java
package multi.jpa.customers;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;

@Entity
public class Customer {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    protected Customer() {
    }

    public Customer(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }

    public interface Repository extends JpaRepository<Customer, Long> {
    }
}
Java
package multi.jpa.billing;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;

@Entity
public class Invoice {
    @Id
    @GeneratedValue
    private Long id;
    private String number;

    protected Invoice() {
    }

    public Invoice(String number) {
        this.number = number;
    }

    @Override
    public String toString() {
        return number;
    }

    public interface Repository extends JpaRepository<Invoice, Long> {
    }
}
Java
package multi.jpa;

import com.zaxxer.hikari.HikariDataSource;
import jakarta.persistence.EntityManagerFactory;
import java.util.Map;
import javax.sql.DataSource;
import multi.jpa.billing.Invoice;
import multi.jpa.customers.Customer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.autoconfigure.DataSourceProperties;
import org.springframework.boot.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.persistence.autoconfigure.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@SpringBootApplication
@EntityScan(basePackageClasses = Customer.class)
public class TwoEntityManagers {

    @Configuration
    @EnableJpaRepositories(basePackageClasses = Customer.class,
            considerNestedRepositories = true)
    static class CustomerJpa {
    }

    @Configuration
    @EnableJpaRepositories(basePackageClasses = Invoice.class,
            considerNestedRepositories = true,
            entityManagerFactoryRef = "billingEntityManagerFactory",
            transactionManagerRef = "billingTransactionManager")
    static class BillingJpa {

        @Bean(defaultCandidate = false)
        @Qualifier("billing")
        @ConfigurationProperties("app.billing.datasource")
        DataSourceProperties billingProperties() {
            return new DataSourceProperties();
        }

        @Bean(defaultCandidate = false)
        @Qualifier("billing")
        HikariDataSource billingDataSource(@Qualifier("billing") DataSourceProperties props) {
            return props.initializeDataSourceBuilder().type(HikariDataSource.class).build();
        }

        @Bean(defaultCandidate = false)
        LocalContainerEntityManagerFactoryBean billingEntityManagerFactory(
                EntityManagerFactoryBuilder builder,
                @Qualifier("billing") DataSource dataSource) {
            return builder.dataSource(dataSource).packages(Invoice.class)
                    .persistenceUnit("billing").build();
        }

        @Bean(defaultCandidate = false)
        JpaTransactionManager billingTransactionManager(
                @Qualifier("billingEntityManagerFactory") EntityManagerFactory emf) {
            return new JpaTransactionManager(emf);
        }
    }

    @Service
    static class Checkout {
        private final Customer.Repository customers;
        private final Invoice.Repository invoices;

        Checkout(Customer.Repository customers, Invoice.Repository invoices) {
            this.customers = customers;
            this.invoices = invoices;
        }

        @Transactional
        public void defaultManager(String name, String invoice) {
            customers.save(new Customer(name));
            invoices.save(new Invoice(invoice));
            throw new IllegalStateException("payment failed");
        }

        @Transactional("billingTransactionManager")
        public void billingManager(String name, String invoice) {
            customers.save(new Customer(name));
            invoices.save(new Invoice(invoice));
            throw new IllegalStateException("payment failed");
        }
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(TwoEntityManagers.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.datasource.url", "jdbc:h2:mem:crm",
                "app.billing.datasource.url", "jdbc:h2:mem:billing"));
        try (var context = app.run(args)) {
            System.out.println("EntityManagerFactory beans: " + String.join(", ",
                    context.getBeanNamesForType(EntityManagerFactory.class)));
            Customer.Repository customers = context.getBean(Customer.Repository.class);
            Invoice.Repository invoices = context.getBean(Invoice.Repository.class);
            Checkout checkout = context.getBean(Checkout.class);

            customers.save(new Customer("Ann"));
            invoices.save(new Invoice("INV-1"));
            System.out.println("customers: " + customers.findAll()
                    + ", invoices: " + invoices.findAll());

            for (String manager : new String[] {"default", "billing"}) {
                try {
                    if (manager.equals("default")) {
                        checkout.defaultManager("Bob", "INV-2");
                    } else {
                        checkout.billingManager("Cara", "INV-3");
                    }
                } catch (IllegalStateException e) {
                    System.out.println("@Transactional with the " + manager
                            + " transaction manager threw; the tables now hold:");
                    System.out.println("  customers: " + customers.findAll()
                            + ", invoices: " + invoices.findAll());
                }
            }
        }
    }
}
Output
EntityManagerFactory beans: billingEntityManagerFactory, entityManagerFactory
customers: [Ann], invoices: [INV-1]
@Transactional with the default transaction manager threw; the tables now hold:
  customers: [Ann], invoices: [INV-1, INV-2]
@Transactional with the billing transaction manager threw; the tables now hold:
  customers: [Ann, Cara], invoices: [INV-1, INV-2]
  • Two factories exist: Spring Boot's entityManagerFactory for customers, restricted to their package by @EntityScan, and billingEntityManagerFactory, built with Spring Boot's EntityManagerFactoryBuilder so that it gets the same spring.jpa.* settings.
  • Each @EnableJpaRepositories scans one package and names the factory and transaction manager its repositories use. Plain saves went to the right database: Ann in CRM, INV-1 in billing.
  • The first checkout method has plain @Transactional, which uses the default transaction manager, bound to CRM. When it threw, Bob's customer row was rolled back, but INV-2 stayed: the invoice repository ran in its own billing transaction, which had already committed.
  • The second method names billingTransactionManager, and the opposite happened: INV-3 was rolled back, and Cara's customer row stayed.

A transaction manager covers one database. A method that writes to both is not atomic, whichever manager it names. The options are to design the work so that it needs one database per transaction, to make the second write idempotent and retried (the outbox pattern is the usual form), or to use a JTA transaction manager with XA-capable drivers, which is heavier and less common today.

Routing reads to a replica

A read replica is a copy of the main database that accepts only reads. Sending read-only transactions to it takes load off the primary. AbstractRoutingDataSource looks like one DataSource, and asks determineCurrentLookupKey() which target to use each time a connection is requested. This router chooses by the transaction's read-only flag. The program tries it in three setups:

Java
package multi.routing;

import java.util.Map;
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class ReadWriteRouting {

    enum Setup { ROUTING_ONLY, ROUTING_BEHIND_LAZY_PROXY, LAZY_PROXY_READ_ONLY_TARGET }

    static Setup setup;

    static DataSource database(String name) {
        DriverManagerDataSource ds = new DriverManagerDataSource(
                "jdbc:h2:mem:" + name + ";DB_CLOSE_DELAY=-1");
        JdbcTemplate jdbc = new JdbcTemplate(ds);
        jdbc.execute("CREATE TABLE IF NOT EXISTS node (name VARCHAR(10))");
        jdbc.update("DELETE FROM node");
        jdbc.update("INSERT INTO node VALUES (?)", name);
        return ds;
    }

    static class ReadWriteDataSource extends AbstractRoutingDataSource {
        @Override
        protected Object determineCurrentLookupKey() {
            boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
            return readOnly ? "replica" : "primary";
        }
    }

    @Configuration
    @EnableTransactionManagement
    static class Config {
        @Bean
        DataSource dataSource() {
            DataSource primary = database("primary");
            DataSource replica = database("replica");
            ReadWriteDataSource routing = new ReadWriteDataSource();
            routing.setTargetDataSources(Map.of("primary", primary, "replica", replica));
            routing.afterPropertiesSet();
            return switch (setup) {
                case ROUTING_ONLY -> routing;
                case ROUTING_BEHIND_LAZY_PROXY -> new LazyConnectionDataSourceProxy(routing);
                case LAZY_PROXY_READ_ONLY_TARGET -> {
                    LazyConnectionDataSourceProxy proxy =
                            new LazyConnectionDataSourceProxy(primary);
                    proxy.setReadOnlyDataSource(replica);
                    yield proxy;
                }
            };
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        JdbcTemplate jdbcTemplate(DataSource dataSource) {
            return new JdbcTemplate(dataSource);
        }

        @Bean
        Catalog catalog(JdbcTemplate jdbc) {
            return new Catalog(jdbc);
        }
    }

    static class Catalog {
        private final JdbcTemplate jdbc;

        Catalog(JdbcTemplate jdbc) {
            this.jdbc = jdbc;
        }

        @Transactional(readOnly = true)
        public String read() {
            return jdbc.queryForObject("SELECT name FROM node", String.class);
        }

        @Transactional
        public String write() {
            return jdbc.queryForObject("SELECT name FROM node", String.class);
        }
    }

    public static void main(String[] args) {
        for (Setup s : Setup.values()) {
            setup = s;
            try (var context = new AnnotationConfigApplicationContext(Config.class)) {
                Catalog catalog = context.getBean(Catalog.class);
                System.out.printf("%-28s read-only -> %-8s read-write -> %s%n",
                        s, catalog.read(), catalog.write());
            }
        }
    }
}
Output
ROUTING_ONLY                 read-only -> primary  read-write -> primary
ROUTING_BEHIND_LAZY_PROXY    read-only -> replica  read-write -> primary
LAZY_PROXY_READ_ONLY_TARGET  read-only -> replica  read-write -> primary
  • ROUTING_ONLY: the read-only method still reached the primary. DataSourceTransactionManager takes the connection at the start of the transaction, before it publishes the read-only flag to TransactionSynchronizationManager. The router asked too early and always saw false.
  • ROUTING_BEHIND_LAZY_PROXY: LazyConnectionDataSourceProxy hands the transaction manager a placeholder connection, and fetches the real one only when the first statement runs. By then the flag is set, so read-only went to the replica and read-write to the primary.
  • LAZY_PROXY_READ_ONLY_TARGET: since Spring Framework 6.1.2, the proxy can do the routing itself with setReadOnlyDataSource. Same result, with no router class.

Replicas usually lag behind the primary by a little. A user who saves a form and is redirected to a page that reads from the replica may not see the change yet. Keep reads that must see the user's own recent writes on the primary, by running them in a read-write transaction.

One database per tenant

Multi-tenant applications that give each customer its own database can route by a tenant id instead of the read-only flag. The id is usually set from the request, for example from a header or the logged-in user, and kept in a ThreadLocal:

Java
package multi.tenant;

import java.util.Map;
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

public class TenantRouting {

    static final ThreadLocal<String> TENANT = new ThreadLocal<>();

    static DataSource tenantDatabase(String tenant) {
        DriverManagerDataSource ds = new DriverManagerDataSource(
                "jdbc:h2:mem:" + tenant + ";DB_CLOSE_DELAY=-1");
        new JdbcTemplate(ds).execute("CREATE TABLE note (text VARCHAR(40))");
        return ds;
    }

    static class TenantDataSource extends AbstractRoutingDataSource {
        @Override
        protected Object determineCurrentLookupKey() {
            return TENANT.get();
        }
    }

    @Configuration
    static class Config {
        @Bean
        DataSource dataSource() {
            TenantDataSource routing = new TenantDataSource();
            routing.setTargetDataSources(Map.of(
                    "acme", tenantDatabase("acme"),
                    "globex", tenantDatabase("globex")));
            routing.setLenientFallback(false);
            return routing;
        }

        @Bean
        JdbcTemplate jdbcTemplate(DataSource dataSource) {
            return new JdbcTemplate(dataSource);
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
    }

    static String notes(JdbcTemplate jdbc, String tenant) {
        TENANT.set(tenant);
        try {
            return tenant + " " + jdbc.queryForList("SELECT text FROM note", String.class);
        } finally {
            TENANT.remove();
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            TransactionTemplate tx = new TransactionTemplate(
                    context.getBean(PlatformTransactionManager.class));

            TENANT.set("acme");
            jdbc.update("INSERT INTO note VALUES ('acme invoice')");
            TENANT.set("globex");
            jdbc.update("INSERT INTO note VALUES ('globex invoice')");
            TENANT.remove();
            System.out.println(notes(jdbc, "acme"));
            System.out.println(notes(jdbc, "globex"));

            System.out.println("-- switching tenant inside one transaction");
            TENANT.set("acme");
            tx.executeWithoutResult(status -> {
                TENANT.set("globex");
                jdbc.update("INSERT INTO note VALUES ('meant for globex')");
            });
            TENANT.remove();
            System.out.println(notes(jdbc, "acme"));
            System.out.println(notes(jdbc, "globex"));

            System.out.println("-- no tenant set");
            try {
                jdbc.queryForList("SELECT text FROM note", String.class);
            } catch (RuntimeException e) {
                Throwable cause = e.getCause() != null ? e.getCause() : e;
                System.out.println(cause.getClass().getSimpleName() + ": "
                        + cause.getMessage());
            }
        }
    }
}
Output
acme [acme invoice]
globex [globex invoice]
-- switching tenant inside one transaction
acme [acme invoice, meant for globex]
globex [globex invoice]
-- no tenant set
IllegalStateException: Cannot determine target DataSource for lookup key [null]
  • With the tenant set before each call, acme's and globex's notes went to their own databases.
  • Inside a transaction, changing the tenant did nothing: the transaction started with acme, the connection was bound to the thread for the whole transaction, and "meant for globex" was written to acme's database.
  • With no tenant, the router refused with Cannot determine target DataSource for lookup key [null], because setLenientFallback(false) was set and no default target was configured. Failing is safer than guessing a tenant.

Set the tenant once, at the edge of the request, before any transaction starts, and clear it in a finally block; a thread pool reuses threads, and a forgotten value leaks into the next request. With JPA, Hibernate has its own multi-tenancy support (MultiTenantConnectionProvider and CurrentTenantIdentifierResolver), which also keeps entities of different tenants apart in its caches.

Other things to check

  • Schema setup: Spring Boot's schema.sql, Flyway and Liquibase support act on the auto-configured DataSource only. For the second database, define its migration bean yourself; Spring Boot's @FlywayDataSource and @LiquibaseDataSource qualifiers pick a different database for the single auto-configured migration.
  • Connection pool sizes: each pool holds its own connections. Two pools of 10 against the same server are 20 connections; size them for the database's limit, not per pool.
  • Tests: @DataJpaTest configures only the auto-configured persistence unit. Import the configuration of the second one into the tests that need it.

Choosing a setup

Which setup fits which need
NeedUse
A second database read or written with SQLA second DataSource and JdbcTemplate, both defaultCandidate = false with a qualifier
Entities in two databasesA second EntityManagerFactory, transaction manager and @EnableJpaRepositories
A change that must update both databasesOne database per transaction plus an outbox or retry; JTA only if it is unavoidable
Read-only traffic sent to a replicaLazyConnectionDataSourceProxy.setReadOnlyDataSource, with @Transactional(readOnly = true) on reads
Complex routing rulesAbstractRoutingDataSource behind a LazyConnectionDataSourceProxy
A database per tenantA routing DataSource keyed by a tenant ThreadLocal, or Hibernate multi-tenancy with JPA

Most of the traps on this page come from two facts: auto-configured beans back off when you define your own, and a transaction is bound to one connection from start to end. The @Transactional page explains the second in detail, and the HikariCP page covers pool settings.