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 DataSourcespring.datasource.*JdbcTemplateEntityManagerFactoryDataSource
Applications use more than one database for different reasons, and each reason has its own setup:
| Setup | What it is | Best for |
|---|---|---|
A second DataSourcedefaultCandidate = false | An extra pool, injected by qualifier, next to the auto-configured one | Reporting, legacy or reference databases used with JDBC |
A second EntityManagerFactory | Separate JPA persistence units, each with its entities, repositories and transaction manager | Two databases that both hold entities |
AbstractRoutingDataSource | One DataSource | Read replicas, one database per tenant |
LazyConnectionDataSourceProxy | Read-only transactions use a second pool | Read 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()
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 DataSourcePropertiesspring.datasource.*
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));
}
}
}
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
beans exist:DataSource , created by Spring Boot fromdataSource , andspring.datasource.* .reportingDataSource - Injecting a
without a qualifier gaveDataSource .orders-pool 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".@Bean(defaultCandidate = false) - The reporting pool took its URL from
and its Hikari settings, such asapp.reporting.datasource.url , frommaximum-pool-size=2 .app.reporting.datasource.hikari.* translatesDataSourceProperties into Hikari'surl .jdbcUrl - The unqualified
reached ORDERS and the qualified one REPORTING. The reportingJdbcTemplate is alsoJdbcTemplate ; the next section shows why that matters.defaultCandidate = false
In Spring Boot 3 code before 3.4, you will see the older pattern instead: both DataSource@Primary
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
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);
}
}
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:
pointed at ORDERS, but the auto-configuredspring.datasource.url was never created. The onlydataSource isDataSource , and Spring Boot built itsreportingDataSource (and JPA, had there been entities) on top of it. Everything silently used REPORTING.JdbcTemplate - A plain JdbcTemplate bean: this time the DataSource was marked
, and both pools exist. But the auto-configureddefaultCandidate = false backed off becausejdbcTemplate exists, so injecting areportingJdbc again gave the reporting one.JdbcTemplate
Neither case fails at startup, which is what makes it dangerous. Mark every extra bean for the second database, whether DataSourceJdbcTemplateEntityManagerFactorydefaultCandidate = false--debug
Two databases with JPA
With entities in both databases, each database needs its own EntityManagerFactory
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> {
}
}
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> {
}
}
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());
}
}
}
}
}
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
for customers, restricted to their package byentityManagerFactory , and@EntityScan , built with Spring Boot'sbillingEntityManagerFactory so that it gets the sameEntityManagerFactoryBuilder settings.spring.jpa.* - Each
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.@EnableJpaRepositories - The first checkout method has plain
, 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.@Transactional - The second method names
, and the opposite happened: INV-3 was rolled back, and Cara's customer row stayed.billingTransactionManager
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
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. AbstractRoutingDataSourceDataSourcedetermineCurrentLookupKey()
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());
}
}
}
}
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.
takes the connection at the start of the transaction, before it publishes the read-only flag toDataSourceTransactionManager . The router asked too early and always sawTransactionSynchronizationManager .false - ROUTING_BEHIND_LAZY_PROXY:
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.LazyConnectionDataSourceProxy - LAZY_PROXY_READ_ONLY_TARGET: since Spring Framework 6.1.2, the proxy can do the routing itself with
. Same result, with no router class.setReadOnlyDataSource
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
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());
}
}
}
}
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
, becauseCannot determine target DataSource for lookup key [null] was set and no default target was configured. Failing is safer than guessing a tenant.setLenientFallback(false)
Set the tenant once, at the edge of the request, before any transaction starts, and clear it in a finallyMultiTenantConnectionProviderCurrentTenantIdentifierResolver
Other things to check
- Schema setup: Spring Boot's
, Flyway and Liquibase support act on the auto-configuredschema.sql only. For the second database, define its migration bean yourself; Spring Boot'sDataSource and@FlywayDataSource qualifiers pick a different database for the single auto-configured migration.@LiquibaseDataSource - 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:
configures only the auto-configured persistence unit. Import the configuration of the second one into the tests that need it.@DataJpaTest
Choosing a setup
| Need | Use |
|---|---|
| A second database read or written with SQL | A second DataSourceJdbcTemplatedefaultCandidate = false |
| Entities in two databases | A second EntityManagerFactory@EnableJpaRepositories |
| A change that must update both databases | One database per transaction plus an outbox or retry; JTA only if it is unavoidable |
| Read-only traffic sent to a replica | LazyConnectionDataSourceProxy.setReadOnlyDataSource@Transactional(readOnly = true) |
| Complex routing rules | AbstractRoutingDataSourceLazyConnectionDataSourceProxy |
| A database per tenant | A routing DataSourceThreadLocal |
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