Video in progress
One service has to write to two different databases through Hibernate (say, the main PostgreSQL and a separate reporting database). How do you organize the configuration and transactions?
A separate DataSource, EntityManagerFactory and TransactionManager for each database, with entity and repository packages clearly separated. I assume there is no atomic write to both databases: the write to the second one goes through an outbox or an async job, idempotently.
📖 Answer
Spring Boot's auto-configuration assumes a single EntityManagerFactory. When you add a second one, you declare everything by hand:
@Configuration
@EnableJpaRepositories(
basePackages = "uz.app.reporting.repo",
entityManagerFactoryRef = "reportingEmf",
transactionManagerRef = "reportingTx")
class ReportingJpaConfig {
@Bean
LocalContainerEntityManagerFactoryBean reportingEmf(
EntityManagerFactoryBuilder b, @Qualifier("reportingDs") DataSource ds) {
return b.dataSource(ds).packages("uz.app.reporting.domain")
.persistenceUnit("reporting").build();
}
@Bean
PlatformTransactionManager reportingTx(@Qualifier("reportingEmf") EntityManagerFactory emf) {
return new JpaTransactionManager(emf);
}
}
The main database gets the same, but with @Primary. The entity packages must not overlap, otherwise one class ends up in two persistence units and validates tables you didn't expect.
The next problem is transactions. @Transactional takes the primary manager by default. On a method that writes to the reporting database you have to write @Transactional("reportingTx") explicitly; if you forget, the repository call runs in its own mini-transaction and the mistake slips through silently.
For atomic writes to both databases at once there is JTA/XA, but I almost never use it: it is slow, complex to set up, and many cloud databases don't fully support it. ChainedTransactionManager is deprecated and does not give real atomicity: if the second commit fails, the first is not rolled back.
The practical way: the write to the main database and the outbox record go in one transaction, and a separate worker copies to the reporting database idempotently. A reporting delay of a few seconds usually bothers nobody, while lost data does.
Sign up to mark studied questions and save your progress.