How to configure multiple databases in MyBatis?
To configure multiple databases in MyBatis, you can follow these steps:
Create multiple data source configurations: For each database, you will need to create a data source configuration in the MyBatis configuration file. You can define a data source using the `
<!-- 数据库 1 的数据源配置 --><dataSource id="dataSource1" type="com.example.DataSourceType">
<!-- 数据库连接信息 -->
</dataSource>
<!-- 数据库 2 的数据源配置 -->
<dataSource id="dataSource2" type="com.example.DataSourceType">
<!-- 数据库连接信息 -->
</dataSource>
Create multiple SqlSessionFactoryBeans: Create a SqlSessionFactoryBean for each data source, and inject the corresponding data source configuration into each SqlSessionFactoryBean separately.
@Configurationpublic class MyBatisConfig {
@Autowired
@Qualifier("dataSource1")
private DataSource dataSource1;
@Autowired
@Qualifier("dataSource2")
private DataSource dataSource2;
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean1() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource1);
// 其他配置...
return sqlSessionFactoryBean;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean2() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource2);
// 其他配置...
return sqlSessionFactoryBean;
}
// 其他配置...
}
3. Create multiple MapperScannerConfigurers: Create a MapperScannerConfigurer for each SqlSessionFactoryBean, and inject the corresponding SqlSessionFactoryBean into each MapperScannerConfigurer separately.
@Configurationpublic class MyBatisConfig {
// ...
@Bean
public MapperScannerConfigurer mapperScannerConfigurer1() {
MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
scannerConfigurer.setBasePackage("com.example.mapper1");
scannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean1");
return scannerConfigurer;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer2() {
MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
scannerConfigurer.setBasePackage("com.example.mapper2");
scannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean2");
return scannerConfigurer;
}
// ...
}
Using different namespaces in MyBatis mapping files: When writing SQL mapping files, it is necessary to use different namespaces to distinguish different databases. This can be specified by adding `
<!-- 数据库 1 的映射文件 --><mapper namespace="com.example.mapper1">
<!-- SQL语句 -->
</mapper>
<!-- 数据库 2 的映射文件 -->
<mapper namespace="com.example.mapper2">
<!-- SQL语句 -->
</mapper>
By following the steps above, you can configure multiple databases in MyBatis, and differentiate them using different data sources, SessionFactories, and namespaces.