实战指南,SpringBoot + Mybatis 如何对接多数据源
在Spring Boot项目中对接多数据源,可以通过以下步骤实现:
- 配置多个数据源
- 创建多个
SqlSessionFactory
和SqlSessionTemplate
实例 - 为每个数据源分别配置Mapper接口
以下是一个简化的示例:
application.properties配置文件
# 第一个数据源配置
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/db1
spring.datasource.primary.username=user1
spring.datasource.primary.password=pass1
# 第二个数据源配置
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/db2
spring.datasource.secondary.username=user2
spring.datasource.secondary.password=pass2
配置类
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
@Bean
public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean
public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
@Bean
public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
Mapper接口
public interface PrimaryMapper {
// 定义操作第一个数据源的方法
}
public interface SecondaryMapper {
// 定义操作第二个数据源的方法
}
Service层
@Service
public class DataService {
private final PrimaryMapper primaryMapper;
private final SecondaryM
评论已关闭