Spring Boot MyBatis 配置 Druid 多数据源

</dependency>

<dependency>

<groupId>org.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

<version>1.3.1</version>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

<dependency>

<groupId>com.oracle</groupId>

<artifactId>ojdbc6</artifactId>

<version>11.2.0.4</version>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

</dependency>

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid-spring-boot-starter</artifactId>

<version>1.1.6</version>

</dependency>

然后根据 application.yml 创建两个数据源配置类 MysqlDatasourceConfig 和 OracleDatasourceConfig:

MysqlDatasourceConfig:

package com.springboot.datasource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

@Configuration

@MapperScan(basePackages = MysqlDatasourceConfig.PACKAGE, sqlSessionFactoryRef = "mysqlSqlSessionFactory")

public class MysqlDatasourceConfig {

// mysqldao 扫描路径

static final String PACKAGE = "com.springboot.mysqldao";

// mybatis mapper 扫描路径

static final String MAPPER_LOCATION = "classpath:mapper/mysql/*.xml";

@Primary

@Bean(name = "mysqldatasource")

@ConfigurationProperties("spring.datasource. 《一线大厂 Java 面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 druid.mysql")

public DataSource mysqlDataSource() {

return DruidDataSourceBuilder.create().build();

}

@Bean(name = "mysqlTransactionManager")

@Primary

public DataSourceTransactionManager mysqlTransactionManager() {

return new DataSourceTransactionManager(mysqlDataSource());

}

@Bean(name = "mysqlSqlSessionFactory")

@Primary

public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqldatasource") DataSource dataSource)

throws Exception {

final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();

sessionFactory.setDataSource(dataSource);

//如果不使用 xml 的方式配置 mapper,则可以省去下面这行 mapper location 的配置。

sessionFactory.setMapperLocations(

new PathMatchingResourcePatternResolver().getResources(MysqlDatasourceConfig.MAPPER_LOCATION));

return sessionFactory.getObject();

}

}

上面代码配置了一个名为 mysqldatasource 的数据源,对应 application.yml 中spring.datasource.druid.mysql前缀配置的数据库。然后创建了一个名为 mysqlSqlSessionFactory 的 Bean,并且注入了 mysqldatasource。与此同时,还分别定了两个扫描路径 PACKAGE 和 MAPPER_LOCATION,前者为 Mysql 数据库对应的 mapper 接口地址,后者为对应的 mapper xml 文件路径。

@Primary标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。多数据源配置的时候,必须要有一个主数据源,用@Primary标志该 Bean。

同理,接着配置 Oracle 数据库对应的配置类:

OracleDatasourceConfig:

@Configuration

@MapperScan(basePackages = OracleDatasourceConfig.PACKAGE,

sqlSessionFactoryRef = "oracleSqlSessionFactory")

public class OracleDatasourceConfig {

// oracledao 扫描路径

static final String PACKAGE = "com.springboot.oracledao";

// mybatis mapper 扫描路径

static final String MAPPER_LOCATION = "classpath:mapper/oracle/*.xml";

@Bean(name = "oracledatasource")

@ConfigurationProperties("spring.datasource.druid.oracle")

public DataSource oracleDataSource() {

return DruidDataSourceBuilder.create().build();

}

@Bean(name = "oracleTransactionManager")

public DataSourceTransactionManager oracleTransactionManager() {

return new DataSourceTransactionManager(oracleDataSource());

}

@Bean(name = "oracleSqlSessionFactory")

public SqlSessionFactory oracleSqlSessionFactory(@Qualifier("oracledatasource") DataSource dataSource)

throws Exception {

final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();

sessionFactory.setDataSource(dataSource);

//如果不使用 xml 的方式配置 mapper,则可以省去下面这行 mapper location 的配置。

sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()

.getResources(OracleDatasourceConfig.MAPPER_LOCATION));

return sessionFactory.getObject();

}

}

配置完多数据源,接下来分别在 com.springboot.mysqldao 路径和 com.springboot.oracledao 路径下创建两个 mapper 接口:

MysqlStudentMapper:

package com.springboot.mysqldao;

import java.util.List;

import java.util.Map;

import org.apache.ibatis.annotations.Mapper;

@Mapper

public interface MysqlStudentMapper {

List<Map<String, Object>> getAllStudents();

}

OracleStudentMapper:

package com.springboot.oracledao;

import java.util.List;

import java.util.Map;

import org.apache.ibatis.annotations.Mapper;

@Mapper

public interface OracleStudentMapper {

List<Map<String, Object>> getAllStudents();

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于使用 MySQL、MyBatisDruid 实现多数据配置,你可以按照以下步骤进行操作: 1. 添加相关依赖:在你的项目中,首先需要添加 MySQL、MyBatisDruid 的相关依赖。你可以在项目的 `pom.xml` 文件中添加以下依赖: ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>版本号</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>版本号</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>版本号</version> </dependency> ``` 请确保将 `版本号` 替换为你所需的实际版本。 2. 配置数据:在 `application.properties` 或 `application.yml` 文件中配置数据的相关信息。以下是一个示例配置: ```yaml spring: datasource: master: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/master_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC username: root password: password slave: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/slave_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC username: root password: password ``` 这里使用了两个数据,一个是 `master`,另一个是 `slave`。你可以根据实际情况进行配置。 3. 配置 Druid 连接池:在 `application.properties` 或 `application.yml` 文件中配置 Druid 连接池的相关信息。以下是一个示例配置: ```yaml spring: datasource: druid: initial-size: 5 min-idle: 5 max-active: 20 test-on-borrow: true validation-query: SELECT 1 ``` 这里配置Druid 连接池的一些常用参数,你可以根据实际需求进行调整。 4. 配置 MyBatis:创建 MyBatis配置文件,例如 `MyBatisConfig.java`,并在其中配置数据和相关的 MyBatis 设置。以下是一个示例配置: ```java @Configuration @MapperScan(basePackages = "com.example.mapper", sqlSessionTemplateRef = "sqlSessionTemplate") public class MyBatisConfig { @Primary @Bean(name = "masterDataSource") @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource masterDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "slaveDataSource") @ConfigurationProperties(prefix = "spring.datasource.slave") public DataSource slaveDataSource() { return DruidDataSourceBuilder.create().build(); } @Primary @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slaveDataSource") DataSource slaveDataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dynamicDataSource(masterDataSource, slaveDataSource)); return sessionFactory.getObject(); } @Bean(name = "sqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean(name = "dynamicDataSource") public DataSource dynamicDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slaveDataSource") DataSource slaveDataSource) { DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource(); Map<Object, Object> dataSourceMap = new HashMap<>(); dataSourceMap.put("master", masterDataSource); dataSourceMap.put("slave", slaveDataSource); dynamicRoutingDataSource.setDefaultTargetDataSource(masterDataSource); dynamicRoutingDataSource.setTargetDataSources(dataSourceMap); return dynamicRoutingDataSource; } } ``` 在这个配置类中,我们创建了两个数据 `masterDataSource` 和 `slaveDataSource`,并将它们注入到 `dynamicDataSource` 中。通过 `DynamicRoutingDataSource` 来实现动态切换数据。 5. 创建 Mapper 接口和 XML 文件:按照正常的 MyBatis 开发流程,创建 Mapper 接口和对应的 XML 文件,并在其中编写 SQL 语句。 完成上述步骤后,你就成功地配置了 MySQL、MyBatisDruid 的多数据。你可以根据需要在不同的业务中使用不同的数据

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值