springbootmybatis多数据源配置
时间: 2025-01-11 10:35:45 浏览: 25
如何在Spring Boot中使用MyBatis进行多数据源配置
1. 添加依赖
为了使项目能够顺利运行并支持多数据源功能,需先调整pom.xml
文件中的依赖项。除了常规的Spring Boot Starter Web和MyBatis外,还需引入用于管理多个数据源的支持库以及数据库驱动程序[^1]。
<dependencies>
<!-- Spring Boot Starters -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Integration with Spring Boot -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- Database Drivers (e.g., MySQL, PostgreSQL) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Additional Data Source Support Libraries -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
</dependencies>
2. application.yml
配置
接下来,在项目的资源目录下创建或编辑application.yml
文件,按照如下格式定义两个不同的数据源及其对应的JDBC URL、用户名和密码等信息:
spring:
datasource:
master:
url: jdbc:mysql://localhost:3306/db_master?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
slave:
url: jdbc:mysql://localhost:3307/db_slave?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
3. 创建自定义的数据源配置类
编写Java代码来动态加载上述YAML文件内的配置参数,并注册到Spring容器内作为Bean对象。这里可以采用继承AbstractRoutingDataSource
的方式来自定义路由逻辑,从而实现在运行期间切换目标数据源的功能[^3]。
@Configuration
public class DataSourceConfig {
@Bean(name = "masterDataSource")
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource masterDataSource() {
return new DruidDataSource();
}
@Bean(name = "slaveDataSource")
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource slaveDataSource() {
return new DruidDataSource();
}
@Primary
@Bean(name = "dynamicDataSource")
public DynamicDataSource dataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
@Qualifier("slaveDataSource") DataSource slaveDataSource){
Map<Object,Object> targetDataSources=new HashMap<>();
targetDataSources.put(DataSourceEnum.MASTER,masterDataSource);
targetDataSources.put(DataSourceEnum.SLAVE,slaveDataSource);
DynamicDataSource dynamicDataSource=new DynamicDataSource();
dynamicDataSource.setTargetDataSources(targetDataSources); // can be more than one data source
dynamicDataSource.setDefaultTargetDataSource(masterDataSource); // default is the write database
return dynamicDataSource;
}
}
4. 定义SQL映射接口和服务层组件
对于每一个具体的业务模块而言,应当分别建立各自的Mapper接口与Service实现类,以便于通过注解的形式指定所使用的特定数据源。例如,可以在DAO层利用@SelectProvider
或其他适当的方式来关联相应的XML文件或者内联语句;而在服务层则可通过@Transactional
配合@DS
注解完成跨库事务处理[^4]。
// Example of a Mapper Interface using Master DB
@Mapper
@DS(value="MASTER")
public interface UserMasterMapper extends BaseMapper<UserEntity> {}
// Service Implementation Class Using Slave DB for Read Operations
@Service
@Transactional(readOnly = true)
@DS("SLAVE")
public class UserServiceImpl implements IUserService {
private final UserSlaveMapper userSlaveMapper;
public List<UserDTO> getAllUsers(){
return this.userSlaveMapper.selectAll().stream()
.map(UserDTO::fromUserEntity).collect(Collectors.toList());
}
}
相关推荐

















