Quick revision
The short answer
For two databases we stop relying on the single auto-configured unit and define, for each database, a DataSource, a LocalContainerEntityManagerFactoryBean and a JpaTransactionManager, marking the orders set @Primary. Each unit gets its own @EnableJpaRepositories with basePackages, entityManagerFactoryRef and transactionManagerRef, so every repository is bound to the right database. Transactions across both units are not atomic without XA, so we design for separate transactions or an outbox, and we provide the pattern as a shared starter and test that each repository really uses its intended unit.
What to remember
In this answer, we built two complete persistence stacks, each with its own DataSource, LocalContainerEntityManagerFactoryBean and JpaTransactionManager, with the orders unit marked @Primary and each set of repositories bound by @EnableJpaRepositories with basePackages, entityManagerFactoryRef and transactionManagerRef. We saw that transactions across the two units are not atomic without XA, so we use separate transactions or an outbox, and we keep the pattern consistent with a shared starter and tests that prove each repository uses its intended unit.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
For two databases we stop relying on the single auto-configured unit and define, for each database, a DataSource, a LocalContainerEntityManagerFactoryBean and a JpaTransactionManager, marking the orders set @Primary. Each unit gets its own @EnableJpaRepositories with basePackages, entityManagerFactoryRef and transactionManagerRef, so every repository is bound to the right database. Transactions across both units are not atomic without XA, so we design for separate transactions or an outbox, and we provide the pattern as a shared starter and test that each repository really uses its intended unit.
Background to this question
Spring Boot makes one database effortless and two databases surprisingly subtle. The mistakes are quiet: a repository that silently uses the wrong database, a @Transactional method that commits the reporting write in a different transaction from the order write, or a property that applies to one unit but not the other. When many applications need the same setup, each team rediscovers these mistakes separately. In this answer, we will build the configuration for two units step by step, see why cross-database transactions are not atomic, and then make the pattern a standard with a starter and tests.
1Why the Auto-Configuration Is Not Enough
Spring Boot's JPA auto-configuration builds exactly one DataSource, one EntityManagerFactory and one transaction manager, and it backs off as soon as we define our own beans of those types. So for two databases we define both sets ourselves. The key idea is that each persistence unit, a set of entities managed by one EntityManagerFactory over one DataSource, is a complete stack, and every repository and every transaction must be tied to exactly one stack.
- Repositories
orders.repo-> orders unit;reporting.repo-> reporting unit - Transaction managers
ordersTx(@Primary),reportingTx - EntityManagerFactories
ordersEmf:orders.model;reportingEmf:reporting.model - DataSourcesorders PostgreSQL, reporting PostgreSQL
4 layers, from the top down. Step through them one at a time.
2Configuring the First Unit
Each unit gets its own configuration class. The orders unit is marked @Primary, so anything that asks for a DataSource, EntityManagerFactory or transaction manager without a qualifier gets the orders one. The EntityManagerFactoryBuilder that Spring Boot provides applies the usual spring.jpa.* settings.
Notice the three references that tie the stack together: basePackages says which repositories belong to this unit, entityManagerFactoryRef says which factory they use, and transactionManagerRef says which transaction manager their methods join. The entity packages in packages() must not overlap with the other unit, or both factories would map the same classes.
3Configuring the Second Unit and Using It
The reporting unit is the same without @Primary and with its own names. Services that write to reporting must name its transaction manager, because @Transactional without a qualifier uses the primary one.
But there is a catch with properties: spring.jpa.properties.* is applied by the shared builder to both units. If the reporting unit needs a different batch size or naming strategy, we pass those properties explicitly when building that unit.
4Transactions Across Both Units Are Not Atomic
A transaction manager controls one resource. If a method writes an order through ordersTx and a report row through reportingTx, they are two transactions. The second commit can fail after the first succeeded, leaving the order without its report row. Distributed transactions with XA and a JTA transaction manager can make both commit or roll back together, but they add a coordinator, slower commits and recovery handling, and few teams want them.
5 messages in order. Play them, or step through them one at a time.
Each transaction manager commits on its own; nothing ties the two outcomes together.
So we design for it. Usually the reporting data is derived from orders, and the outbox pattern fits well: the order transaction also inserts an event row in an outbox table in the orders database, and a separate process reads the outbox and writes the reporting database, retrying until it succeeds. The report becomes eventually consistent, but nothing is lost.
5Making It a Standard Across Teams
Copying this configuration into every application spreads small mistakes: a missing @Primary, overlapping packages, a forgotten transactionManager qualifier. A shared starter, an internal Spring Boot auto-configuration library, can create named persistence units from properties, such as app.persistence.units.orders.packages, with consistent defaults for pools, naming and Hibernate settings. Teams declare their units instead of writing the beans.
The pattern must also be tested. Each application gets a test that starts the context with two Testcontainers databases and checks that every repository writes to the database it should, and that each @Transactional method uses the intended manager.
6Follow-up questions
Can one repository use both databases?
No. A repository is bound to one EntityManagerFactory through the @EnableJpaRepositories that registered it. If a use case needs data from both, a service calls one repository from each unit, in separate transactions.
Is ChainedTransactionManager a solution?
It was a Spring Data utility that commits several transaction managers one after another, and it is deprecated. It does not make commits atomic; it only orders them, so a failure between the commits still leaves partial results.
How do migrations work with two databases?
Each database gets its own Flyway or Liquibase configuration and migration folder. Spring Boot's auto-configured Flyway handles only the primary DataSource, so the second one needs its own Flyway bean, which the shared starter can provide too.
7Conclusion
In this answer, we built two complete persistence stacks, each with its own DataSource, LocalContainerEntityManagerFactoryBean and JpaTransactionManager, with the orders unit marked @Primary and each set of repositories bound by @EnableJpaRepositories with basePackages, entityManagerFactoryRef and transactionManagerRef. We saw that transactions across the two units are not atomic without XA, so we use separate transactions or an outbox, and we keep the pattern consistent with a shared starter and tests that prove each repository uses its intended unit.
Open with
Spring Boot's auto-configuration only builds one persistence unit and backs off when I define my own beans, so for two databases I define two complete stacks. For each database I create a DataSource, usually from its own DataSourceProperties prefix, a LocalContainerEntityManagerFactoryBean with its own entity packages and persistence unit name, and a JpaTransactionManager for that factory.
Then, if they want more
I mark the orders set Primary, so anything injected without a qualifier gets orders. Then each unit gets its own EnableJpaRepositories with basePackages for its repositories, entityManagerFactoryRef and transactionManagerRef, which binds every repository to exactly one database. Services writing to reporting use Transactional with transactionManager equals reportingTx, otherwise they get the primary manager.
The important design point is that a method writing to both databases runs two independent transactions; the second commit can fail after the first. I would not reach for XA by default. If reporting is derived from orders, I would use an outbox: write an event row in the orders transaction and have a relay update reporting with retries.
To keep this standard across teams, I would package the configuration as an internal starter where teams declare units in properties, with consistent pool and Hibernate defaults, and require a test with two Testcontainers databases that checks each repository writes to its intended database.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Boot 4
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Several applications need two databases each (one PostgreSQL for orders, one for...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/7f08deb610/