要在 MyBatis 中配置多個數據庫,你可以按照以下步驟進行操作:
1. 創建多個數據源配置:對于每個數據庫,你需要在 MyBatis 配置文件中創建一個數據源配置??梢酝ㄟ^ `<dataSource>` 元素來定義一個數據源,其中包含數據庫連接信息,例如 URL、用戶名和密碼等。你可以為每個數據源設置不同的 id,以便在后續步驟中引用它們。
<!-- 數據庫 1 的數據源配置 --><dataSource id="dataSource1" type="com.example.DataSourceType">
<!-- 數據庫連接信息 -->
</dataSource>
<!-- 數據庫 2 的數據源配置 -->
<dataSource id="dataSource2" type="com.example.DataSourceType">
<!-- 數據庫連接信息 -->
</dataSource>
2. 創建多個 SqlSessionFactoryBean:為每個數據源創建一個 `SqlSessionFactoryBean`,并分別將相應的數據源配置注入到各個 `SqlSessionFactoryBean` 中。
@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. 創建多個 MapperScannerConfigurer:為每個 `SqlSessionFactoryBean` 創建一個 `MapperScannerConfigurer`,并分別將相應的 `SqlSessionFactoryBean` 注入到各個 `MapperScannerConfigurer` 中。
@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;
}
// ...
}
4. 在 MyBatis 映射文件中使用不同的命名空間:在編寫 SQL 映射文件時,需要使用不同的命名空間來區分不同的數據庫??梢酝ㄟ^在映射文件中添加 `<mapper namespace="com.example.mapper1">` 或者 `<mapper namespace="com.example.mapper2">` 來指定命名空間。
<!-- 數據庫 1 的映射文件 --><mapper namespace="com.example.mapper1">
<!-- SQL語句 -->
</mapper>
<!-- 數據庫 2 的映射文件 -->
<mapper namespace="com.example.mapper2">
<!-- SQL語句 -->
</mapper>
通過以上步驟,你就可以在 MyBatis 中配置多個數據庫,并且使用不同的數據源、SessionFactory 和命名空間來區分它們。