mybatis配置多个数据源

https://www.jb51.net/article/114775.htm

好的,以下是使用 Spring Boot 配置多个 MyBatis 数据源的示例代码: 首先,我们需要在 `application.properties` 文件中配置多个数据源的相关信息: ```properties # 配置第一个数据源 spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1 spring.datasource.primary.username=username1 spring.datasource.primary.password=password1 spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver # 配置第二个数据源 spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2 spring.datasource.secondary.username=username2 spring.datasource.secondary.password=password2 spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver ``` 接下来,我们需要创建多个数据源的 `DataSource` 对象,并将其注入到 `SqlSessionFactory` 中: ```java @Configuration @MapperScan(basePackages = "com.example.mapper", sqlSessionTemplateRef = "primarySqlSessionTemplate") public class PrimaryDataSourceConfig { @Bean @Primary @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @Primary public SqlSessionFactory primarySqlSessionFactory() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(primaryDataSource()); return factoryBean.getObject(); } @Bean @Primary public SqlSessionTemplate primarySqlSessionTemplate() throws Exception { return new SqlSessionTemplate(primarySqlSessionFactory()); } } @Configuration @MapperScan(basePackages = "com.example.mapper", sqlSessionTemplateRef = "secondarySqlSessionTemplate") public class SecondaryDataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactory secondarySqlSessionFactory() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(secondaryDataSource()); return factoryBean.getObject(); } @Bean public SqlSessionTemplate secondarySqlSessionTemplate() throws Exception { return new SqlSessionTemplate(secondarySqlSessionFactory()); } } ``` 这里我们使用 `@MapperScan` 注解扫描 `com.example.mapper` 包下的所有 Mapper 接口,并使用 `sqlSessionTemplateRef` 属性指定使用哪个 `SqlSessionTemplate`。 最后,在 Mapper 接口中使用 `@Qualifier` 注解指定使用哪个数据源: ```java @Mapper @Qualifier("primarySqlSessionTemplate") public interface PrimaryMapper { // ... } @Mapper @Qualifier("secondarySqlSessionTemplate") public interface SecondaryMapper { // ... } ``` 以上就是使用 Spring Boot 配置多个 MyBatis 数据源的示例代码,希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值