springboot:mybatis配置多数据源

Posted 小溪(潺潺流水,润泽千里)

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot:mybatis配置多数据源相关的知识,希望对你有一定的参考价值。

第一个数据源:

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

@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class PropertiesDatasource {

  private String driverClassName;
  private String url;
  private String username;
  private String password;
  private String connectionProperties;
  private Integer initialSize = 1;
  private Integer minIdle = 3;
  private Integer maxActive = 20;
  private Integer timeBetweenEvictionRunsMillis = 60000;
  private Integer minEvictableIdleTimeMillis = 300000;
  private Boolean testWhileIdle = true;
  private String validationQuery = null;
  private Boolean testOnBorrow = false;
  private Boolean testOnReturn = false;
  private Boolean poolPreparedStatements = true;
  private Integer maxPoolPreparedStatementPerConnectionSize = 20;
  private String filters = "stat";

  public final String getDriverClassName() {
    return driverClassName;
  }

  public final void setDriverClassName(String driverClassName) {
    this.driverClassName = driverClassName;
  }

  public final String getUrl() {
    return url;
  }

  public final void setUrl(String url) {
    this.url = url;
  }

  public final String getUsername() {
    return username;
  }

  public final void setUsername(String username) {
    this.username = username;
  }

  public final String getPassword() {
    return password;
  }

  public final void setPassword(String password) {
    this.password = password;
  }

  public final String getConnectionProperties() {
    return connectionProperties;
  }

  public final void setConnectionProperties(String connectionProperties) {
    this.connectionProperties = connectionProperties;
  }

  public final Integer getInitialSize() {
    return initialSize;
  }

  public final void setInitialSize(Integer initialSize) {
    this.initialSize = initialSize;
  }

  public final Integer getMinIdle() {
    return minIdle;
  }

  public final void setMinIdle(Integer minIdle) {
    this.minIdle = minIdle;
  }

  public final Integer getMaxActive() {
    return maxActive;
  }

  public final void setMaxActive(Integer maxActive) {
    this.maxActive = maxActive;
  }

  public final Integer getTimeBetweenEvictionRunsMillis() {
    return timeBetweenEvictionRunsMillis;
  }

  public final void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) {
    this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
  }

  public final Integer getMinEvictableIdleTimeMillis() {
    return minEvictableIdleTimeMillis;
  }

  public final void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
    this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
  }

  public final Boolean getTestWhileIdle() {
    return testWhileIdle;
  }

  public final void setTestWhileIdle(Boolean testWhileIdle) {
    this.testWhileIdle = testWhileIdle;
  }

  public final String getValidationQuery() {
    return validationQuery;
  }

  public final void setValidationQuery(String validationQuery) {
    this.validationQuery = validationQuery;
  }

  public final Boolean getTestOnBorrow() {
    return testOnBorrow;
  }

  public final void setTestOnBorrow(Boolean testOnBorrow) {
    this.testOnBorrow = testOnBorrow;
  }

  public final Boolean getTestOnReturn() {
    return testOnReturn;
  }

  public final void setTestOnReturn(Boolean testOnReturn) {
    this.testOnReturn = testOnReturn;
  }

  public final Boolean getPoolPreparedStatements() {
    return poolPreparedStatements;
  }

  public final void setPoolPreparedStatements(Boolean poolPreparedStatements) {
    this.poolPreparedStatements = poolPreparedStatements;
  }

  public final Integer getMaxPoolPreparedStatementPerConnectionSize() {
    return maxPoolPreparedStatementPerConnectionSize;
  }

  public final void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
    this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
  }

  public final String getFilters() {
    return filters;
  }

  public final void setFilters(String filters) {
    this.filters = filters;
  }

}
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;
import com.csget.properties.PropertiesDatasource;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "com.test.dao", sqlSessionTemplateRef = "sqlSessionTemplate")
public class ConfigDataSource {

  private Logger logger = LoggerFactory.getLogger(ConfigDataSource.class);

  @Autowired
  private PropertiesDatasource propertiesDatasource;

  @Bean(name = "dataSource")
  @Primary
  public DataSource dataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl(propertiesDatasource.getUrl());
    dataSource.setDriverClassName(propertiesDatasource.getDriverClassName());
    dataSource.setUsername(propertiesDatasource.getUsername());
    dataSource.setPassword(propertiesDatasource.getPassword());
    if (StringUtils.isNotBlank(propertiesDatasource.getConnectionProperties())) {
      dataSource.setConnectionProperties(propertiesDatasource.getConnectionProperties());
    }
    dataSource.setInitialSize(propertiesDatasource.getInitialSize());
    dataSource.setMinIdle(propertiesDatasource.getMinIdle());
    dataSource.setMaxWait(propertiesDatasource.getMaxActive());
    dataSource.setMaxActive(propertiesDatasource.getMaxActive());
    dataSource.setTimeBetweenEvictionRunsMillis(propertiesDatasource.getTimeBetweenEvictionRunsMillis());
    dataSource.setMinEvictableIdleTimeMillis(propertiesDatasource.getMinEvictableIdleTimeMillis());
    dataSource.setTestWhileIdle(propertiesDatasource.getTestWhileIdle());
    if(StringUtils.isNotBlank(propertiesDatasource.getValidationQuery())) {
      dataSource.setValidationQuery(propertiesDatasource.getValidationQuery());
    }
    dataSource.setTestOnBorrow(propertiesDatasource.getTestOnBorrow());
    dataSource.setTestOnReturn(propertiesDatasource.getTestOnReturn());
    dataSource.setPoolPreparedStatements(propertiesDatasource.getPoolPreparedStatements());
    dataSource.setMaxPoolPreparedStatementPerConnectionSize(
        propertiesDatasource.getMaxPoolPreparedStatementPerConnectionSize());
    if (StringUtils.isNotBlank(propertiesDatasource.getFilters())) {
      try {
        dataSource.setFilters(propertiesDatasource.getFilters());
      } catch (SQLException e) {
        logger.error("初始化数据库连接池发生异常:{}", e.toString());
      }
    }
    return dataSource;
  }

  @Bean(name = "sqlSessionFactory")
  @Primary
  public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setConfigLocation(
        new PathMatchingResourcePatternResolver().getResource("classpath:config/mybatis-config.xml"));
    bean.setMapperLocations(
        new PathMatchingResourcePatternResolver().getResources("classpath*:com/csget/dao/xml/**/*.xml"));
    return bean.getObject();
  }

  @Bean(name = "transactionManager")
  @Primary
  public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

  @Bean(name = "sqlSessionTemplate")
  @Primary
  public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory)
      throws Exception {
    return new SqlSessionTemplate(sqlSessionFactory);
  }

}

第二个数据源:

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

@Component
@ConfigurationProperties(prefix = "spring.datasource.history")
public class PropertiesDatasourceHistory {

  private String driverClassName;
  private String url;
  private String username;
  private String password;
  private String connectionProperties;
  private Integer initialSize = 1;
  private Integer minIdle = 3;
  private Integer maxActive = 20;
  private Integer timeBetweenEvictionRunsMillis = 60000;
  private Integer minEvictableIdleTimeMillis = 300000;
  private Boolean testWhileIdle = true;
  private String validationQuery = null;
  private Boolean testOnBorrow = false;
  private Boolean testOnReturn = false;
  private Boolean poolPreparedStatements = true;
  private Integer maxPoolPreparedStatementPerConnectionSize = 20;
  private String filters = "stat";

  public final String getDriverClassName() {
    return driverClassName;
  }

  public final void setDriverClassName(String driverClassName) {
    this.driverClassName = driverClassName;
  }

  public final String getUrl() {
    return url;
  }

  public final void setUrl(String url) {
    this.url = url;
  }

  public final String getUsername() {
    return username;
  }

  public final void setUsername(String username) {
    this.username = username;
  }

  public final String getPassword() {
    return password;
  }

  public final void setPassword(String password) {
    this.password = password;
  }

  public final String getConnectionProperties() {
    return connectionProperties;
  }

  public final void setConnectionProperties(String connectionProperties) {
    this.connectionProperties = connectionProperties;
  }

  public final Integer getInitialSize() {
    return initialSize;
  }

  public final void setInitialSize(Integer initialSize) {
    this.initialSize = initialSize;
  }

  public final Integer getMinIdle() {
    return minIdle;
  }

  public final void setMinIdle(Integer minIdle) {
    this.minIdle = minIdle;
  }

  public final Integer getMaxActive() {
    return maxActive;
  }

  public final void setMaxActive(Integer maxActive) {
    this.maxActive = maxActive;
  }

  public final Integer getTimeBetweenEvictionRunsMillis() {
    return timeBetweenEvictionRunsMillis;
  }

  public final void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) {
    this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
  }

  public final Integer getMinEvictableIdleTimeMillis() {
    return minEvictableIdleTimeMillis;
  }

  public final void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
    this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
  }

  public final Boolean getTestWhileIdle() {
    return testWhileIdle;
  }

  public final void setTestWhileIdle(Boolean testWhileIdle) {
    this.testWhileIdle = testWhileIdle;
  }

  public final String getValidationQuery() {
    return validationQuery;
  }

  public final void setValidationQuery(String validationQuery) {
    this.validationQuery = validationQuery;
  }

  public final Boolean getTestOnBorrow() {
    return testOnBorrow;
  }

  public final void setTestOnBorrow(Boolean testOnBorrow) {
    this.testOnBorrow = testOnBorrow;
  }

  public final Boolean getTestOnReturn() {
    return testOnReturn;
  }

  public final void setTestOnReturn(Boolean testOnReturn) {
    this.testOnReturn = testOnReturn;
  }

  public final Boolean getPoolPreparedStatements() {
    return poolPreparedStatements;
  }

  public final void setPoolPreparedStatements(Boolean poolPreparedStatements) {
    this.poolPreparedStatements = poolPreparedStatements;
  }

  public final Integer getMaxPoolPreparedStatementPerConnectionSize() {
    return maxPoolPreparedStatementPerConnectionSize;
  }

  public final void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
    this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
  }

  public final String getFilters() {
    return filters;
  }

  public final void setFilters(String filters) {
    this.filters = filters;
  }

}
/**
 * 
 * 类描述: 历史库
 *
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "com.test.history.dao", sqlSessionTemplateRef = "sqlSessionTemplateHistory")
public class ConfigDataSourceHistory {

  private Logger logger = LoggerFactory.getLogger(ConfigDataSourceHistory.class);

  @Autowired
  private PropertiesDatasourceHistory propertiesDatasourceHistory;

  @Bean(name = "dataSourceHistory")
  public DataSource dataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl(propertiesDatasourceHistory.getUrl());
    dataSource.setDriverClassName(propertiesDatasourceHistory.getDriverClassName());
    dataSource.setUsername(propertiesDatasourceHistory.getUsername());
    dataSource.setPassword(propertiesDatasourceHistory.getPassword());
    if (StringUtils.isNotBlank(propertiesDatasourceHistory.getConnectionProperties())) {
      dataSource.setConnectionProperties(propertiesDatasourceHistory.getConnectionProperties());
    }
    dataSource.setInitialSize(propertiesDatasourceHistory.getInitialSize());
    dataSource.setMinIdle(propertiesDatasourceHistory.getMinIdle());
    dataSource.setMaxWait(propertiesDatasourceHistory.getMaxActive());
    dataSource.setMaxActive(propertiesDatasourceHistory.getMaxActive());
    dataSource.setTimeBetweenEvictionRunsMillis(propertiesDatasourceHistory.getTimeBetweenEvictionRunsMillis());
    dataSource.setMinEvictableIdleTimeMillis(propertiesDatasourceHistory.getMinEvictableIdleTimeMillis());
    dataSource.setTestWhileIdle(propertiesDatasourceHistory.getTestWhileIdle());
    if (StringUtils.isNotBlank(propertiesDatasourceHistory.getValidationQuery())) {
      dataSource.setValidationQuery(propertiesDatasourceHistory.getValidationQuery());
    }
    dataSource.setTestOnBorrow(propertiesDatasourceHistory.getTestOnBorrow());
    dataSource.setTestOnReturn(propertiesDatasourceHistory.getTestOnReturn());
    dataSource.setPoolPreparedStatements(propertiesDatasourceHistory.getPoolPreparedStatements());
    dataSource.setMaxPoolPreparedStatementPerConnectionSize(
        propertiesDatasourceHistory.getMaxPoolPreparedStatementPerConnectionSize());
    if (StringUtils.isNotBlank(propertiesDatasourceHistory.getFilters())) {
      try {
        dataSource.setFilters(propertiesDatasourceHistory.getFilters());
      } catch (SQLException e) {
        logger.error("初始化数据库连接池发生异常:{}", e.toString());
      }
    }
    return dataSource;
  }

  @Bean(name = "sqlSessionFactoryHistory")
  public SqlSessionFactory sqlSessionFactoryHistory(@Qualifier("dataSourceHistory") DataSource dataSourceHistory) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSourceHistory);
    bean.setConfigLocation(
        new PathMatchingResourcePatternResolver().getResource("classpath:config/mybatis-config.xml"));
    bean.setMapperLocations(
        new PathMatchingResourcePatternResolver().getResources("classpath*:com/csget/history/dao/xml/**/*.xml"));
    return bean.getObject();
  }

  @Bean(name = "transactionManagerHistory")
  public DataSourceTransactionManager transactionManagerHistory(@Qualifier("dataSourceHistory") DataSource dataSourceHistory) {
    return new DataSourceTransactionManager(dataSourceHistory);
  }

  @Bean(name = "sqlSessionTemplateHistory")
  public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactoryHistory") SqlSessionFactory sqlSessionFactoryHistory)
      throws Exception {
    return new SqlSessionTemplate(sqlSessionFactoryHistory);
  }

}

注意:

  @Primary 这个注解只能存在于一个数据源中。

以上是关于springboot:mybatis配置多数据源的主要内容,如果未能解决你的问题,请参考以下文章

springboot+mybatis多数据源配置

springBoot+mybatis多数据源配置

springboot:mybatis配置多数据源

SpringBoot+Mybatis配置多数据源,分包方式

springboot、mybatis-plus、Druid多数据源环境搭建

19.springboot+mybatis多数据源