mybatis-plus多数据源配置整合druid

1.导入jar包

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/dynamic-datasource-spring-boot-starter -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.11</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

2.配置yml

# 数据源配置
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    druid:
      webStatFilter:
        enabled: true
      stat-view-servlet:
        enabled: true                   # 启用StatViewServlet
        url-pattern: /druid/*           # 访问内置监控页面的路径,内置监控页面的首页是/druid/index.html
        # 控制台管理用户名和密码
        login-username: root
        login-password: 123456
      filter:
        stat:
          enabled: true
          # 慢SQL记录
          log-slow-sql: true
          slow-sql-millis: 1000
          merge-sql: true
        wall:
          config:
            multi-statement-allow: true
    dynamic:
      primary: db1
      strict: false
      druid:
        filters: stat,wall
        # 配置初始化大小、最小、最大
        initial-size: 5
        min-idle: 5
        max-active: 20
        # 配置获取连接等待超时的时间(单位:毫秒)
        max-wait: 60000
        # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        time-between-eviction-runs-millis: 2000
        # 配置一个连接在池中最小生存的时间,单位是毫秒
        min-evictable-idle-time-millis: 600000
        # 用来测试连接是否可用的SQL语句,默认值每种数据库都不相同,这是mysql
        validation-query: select 1
        # 应用向连接池申请连接,并且testOnBorrow为false时,连接池将会判断连接是否处于空闲状态,如果是,则验证这条连接是否可用
        test-whileIdle: true
        # 如果为true,默认是false,应用向连接池申请连接时,连接池会判断这条连接是否是可用的
        test-on-borrow: true
        # 如果为true(默认false),当应用使用完连接,连接池回收连接的时候会判断该连接是否还可用
        test-on-return: true
        # 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle
        pool-prepared-statements: true
        # 要启用PSCache,必须配置大于0,当大于0时, poolPreparedStatements自动触发修改为true,
        # 在Druid中,不会存在Oracle下PSCache占用内存过多的问题,
        # 可以把这个数值配置大一些,比如说100
        max-pool-prepared-statement-per-connection-size: 20
        # 连接池中的minIdle数量以内的连接,空闲时间超过minEvictableIdleTimeMillis,则会执行keepAlive操作
        keep-alive: true
      datasource:
        db1:
          url: jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
          username: username
          password: password
          driver-class-name: com.mysql.cj.jdbc.Driver
        db2:
          url: jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
          username: username
          password: password
          driver-class-name: com.mysql.cj.jdbc.Driver

3.从本地数据库加在数据源

port com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;

import java.sql.ResultSet;import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedHashMap;
import java.util.Map;

public class MyDataSource extends AbstractJdbcDataSourceProvider {

    private static final Log log = LogFactory.getLog(MyDataSource.class);

    public MyDataSource(@Value("spring.datasource.driver-class-name") String driverClassName,
                        @Value("spring.datasource.url") String url,
                        @Value("spring.datasource.username") String username,
                        @Value("spring.datasource.password") String password) {
        super(driverClassName, url, username, password);
    }

    @Override
    protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
        ResultSet resultSet = statement.executeQuery("SELECT * FROM data_source_config WHERE status = 1");
        Map<String, DataSourceProperty> dataSources = new LinkedHashMap<>();
        while (resultSet.next()) {
            String dataSourceName = resultSet.getString("dataSourceName");
            String driverClassName = resultSet.getString("driverClassName");
            String url = resultSet.getString("url");
            String username = resultSet.getString("username");
            String password = resultSet.getString("password");
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            dataSourceProperty.setDriverClassName(driverClassName);
            dataSourceProperty.setUrl(url);
            dataSourceProperty.setUsername(username);
            dataSourceProperty.setPassword(password);
            dataSources.put(dataSourceName, dataSourceProperty);
        }
        return dataSources;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Mybatis-plus 可以通过在配置文件中配置多个数据来实现多数据的支持。 1. 在 application.yml 或者 application.properties 中配置多个数据,如: ``` spring: datasource: master: url: jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver slave: url: jdbc:mysql://localhost:3306/slave?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` 2. 在 mybatis-plus配置类中,通过注解 @ConfigurationProperties(prefix = "spring.datasource.master") 来指定使用哪个数据。 3. 在 Service 中通过注解 @DS("slave") 来指定使用从库, @DS("master") 来指定使用主库。 参考代码: ``` @Configuration @MapperScan(basePackages = "com.example.mapper", sqlSessionTemplateRef = "slaveSqlSessionTemplate") @ConfigurationProperties(prefix = "spring.datasource.slave") public class SlaveDataSourceConfig { @Bean(name = "slaveDataSource") public DataSource dataSource() { return new DruidDataSource(); } @Bean(name = "slaveSqlSessionFactory") public SqlSessionFactory sqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "slaveSqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } } @Service @DS("slave") public class TestService { @Autowired private TestMapper testMapper; public List<Test> getAll() { return testMapper.selectList(null); } } ``` 需要注意的是,使用多数据需要在项目中引入 mybatis-plus-extension 包,并且需要配置数据的事务管理器。 ### 回答2: Mybatis-plus是一个流行的Mybatis增强工具包,允许开发人员更容易地与数据库进行交互。在实际开发中,我们可能需要使用多个数据来达到不同的业务需求。下面是配置Mybatis-plus数据的详细步骤。 1. 添加多数据配置项 在application.yml中添加多个数据配置,例如: ```yaml # 主数据配置 spring.datasource.master.url=jdbc:mysql://localhost:3306/master spring.datasource.master.username=root spring.datasource.master.password=root # 从数据配置 spring.datasource.slave.url=jdbc:mysql://localhost:3306/slave spring.datasource.slave.username=root spring.datasource.slave.password=root ``` 2. 创建数据对象 Mybatis-plus需要使用DruidDataSource数据对象,因此需要创建多个数据对象用于连接主从数据库。我们可以使用@Primary注解指定默认的数据。 ```java @Configuration public class DataSourceConfig { @Primary @Bean @ConfigurationProperties("spring.datasource.master") public DataSource masterDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.slave") public DataSource slaveDataSource() { return DruidDataSourceBuilder.create().build(); } } ``` 3. 配置Mybatis-plus的SqlSessionFactory和SqlSessionTemplate 我们需要为每个数据创建SqlSessionFactory和SqlSessionTemplate。Mybatis-plus提供了MybatisSqlSessionFactoryBean和MybatisSqlSessionTemplate两个类,用于创建Mybatis的SqlSessionFactory和SqlSessionTemplate对象。 ```java @Configuration @MapperScan(basePackages = {"com.example.mapper"}) public class MybatisConfig { @Primary @Bean public MybatisSqlSessionFactoryBean masterSqlSessionFactory( @Qualifier("masterDataSource") DataSource dataSource ) throws Exception { MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); return factoryBean; } @Bean public MybatisSqlSessionTemplate masterSqlSessionTemplate( @Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory ) { return new MybatisSqlSessionTemplate(sqlSessionFactory); } @Bean public MybatisSqlSessionFactoryBean slaveSqlSessionFactory( @Qualifier("slaveDataSource") DataSource dataSource ) throws Exception { MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); return factoryBean; } @Bean public MybatisSqlSessionTemplate slaveSqlSessionTemplate( @Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory ) { return new MybatisSqlSessionTemplate(sqlSessionFactory); } } ``` 4. 创建多数据的Mapper接口 我们需要为每个数据创建一个Mapper接口,用于访问相应的数据库。可以使用@Mapper注解将Mapper接口注册到Spring容器中。同时,我们需要使用@Qualifier注解指定具体的SqlSessionTemplate来操作不同的数据库。 ```java @Mapper @Component public interface MasterMapper { @Select("SELECT count(*) FROM user") int countUser(); } @Mapper @Component public interface SlaveMapper { @Select("SELECT count(*) FROM book") int countBook(); } ``` 5. 测试使用多数据 我们可以在业务代码中使用注入的Mapper来操作主从数据库,例如: ```java @Service public class TestService { @Autowired @Qualifier("masterSqlSessionTemplate") private SqlSessionTemplate masterSqlSessionTemplate; @Autowired @Qualifier("slaveSqlSessionTemplate") private SqlSessionTemplate slaveSqlSessionTemplate; public int countUser() { return masterSqlSessionTemplate.getMapper(MasterMapper.class).countUser(); } public int countBook() { return slaveSqlSessionTemplate.getMapper(SlaveMapper.class).countBook(); } } ``` 通过以上步骤,我们成功地配置Mybatis-plus的多数据。在实际开发中,如果需要使用更多的数据,只需按照以上方法添加即可。 ### 回答3: Mybatis-plus是一个基于Mybatis的一款全面功能和增强功能的ORM框架,它可以简化Java开发人员在不同的数据库之间切换的过程。在Mybatis-plus中,我们可以很容易的配置数据,以满足应用中不同业务所需的数据。 下面,我们来详细了解Mybatis-plus配置数据的步骤: 1. 导入依赖 在pom.xml文件中导入Mybatis-plus和对应的数据库驱动依赖,如下所示: ```xml <!-- Mybatis-plus依赖 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus-version}</version> </dependency> <!-- MySQL驱动依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ``` 2. 配置数据 在application.properties文件中配置数据,如下所示: ```properties ## 主数据 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/db1 spring.datasource.username=root spring.datasource.password=123456 ## 次数据 spring.second.datasource.driver-class-name=com.mysql.jdbc.Driver spring.second.datasource.url=jdbc:mysql://localhost:3306/db2 spring.second.datasource.username=root spring.second.datasource.password=123456 ``` 3. 配置数据Mybatis-plus配置文件中,我们通过定义多个数据配置来实现多数据的功能,如下所示: ```java @Configuration @MapperScan(basePackages = {"com.example.mapper1", "com.example.mapper2"}, sqlSessionTemplateRef = "sqlSessionTemplate") public class MybatisPlusConfig { @Bean(name = "dataSource") @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "secondDataSource") @ConfigurationProperties(prefix = "spring.second.datasource") public DataSource secondDataSource() { return DataSourceBuilder.create().build(); } @Primary @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml")); return sqlSessionFactoryBean.getObject(); } @Bean(name = "secondSqlSessionFactory") public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml")); return sqlSessionFactoryBean.getObject(); } @Bean(name = "transactionManager") public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "secondTransactionManager") public DataSourceTransactionManager secondTransactionManager(@Qualifier("secondDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "sqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } @Bean(name = "secondSqlSessionTemplate") public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` 在上述代码中,我们定义了两个数据dataSource和secondDataSource,并分别配置了两个SqlSessionFactory、两个DataSourceTransactionManager以及两个SqlSessionTemplate。通过这种方式,就可以在应用中轻松切换不同的数据,以满足应用中不同业务的需求。 总之,Mybatis-plus提供了非常简单的方式来配置数据,具体实现过程如上所示。对于开发者来说,如果要实现多数据的切换,除了了解上述配置方式之外,还需要记住在使用时如何切换数据,一定要注意正确使用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值