Hibernate / MyBatis Interview questions
How do you use MyBatis with multiple data sources?
Supporting multiple databases in a single MyBatis application generally means configuring a separate SqlSessionFactory (and corresponding DataSource) per database, with mappers explicitly associated with the correct factory rather than assuming a single, application-wide default.
@Configuration @MapperScan(basePackages = "com.example.mapper.primary", sqlSessionFactoryRef = "primarySqlSessionFactory") public class PrimaryDataSourceConfig { @Bean @Primary public DataSource primaryDataSource() { /* ... */ } @Bean public SqlSessionFactory primarySqlSessionFactory(DataSource primaryDataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(primaryDataSource); return factoryBean.getObject(); } }
In a Spring Boot application, this typically means defining separate @Configuration classes for each data source, each with its own DataSource, SqlSessionFactory, and @MapperScan pointed at a distinct base package — the sqlSessionFactoryRef attribute is what ties a specific package of mapper interfaces to the correct factory, so mappers for database A aren't accidentally wired against database B's connection.
Transaction management also needs care in a multi-data-source setup: each data source typically needs its own PlatformTransactionManager bean, and operations spanning both databases within a single logical transaction generally require a distributed transaction manager (like JTA) rather than Spring's simpler, single-resource @Transactional handling, since a plain local transaction manager can't atomically coordinate commits across two entirely separate database connections.
More Related questions...