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 这个注解只能存在于一个数据源中。

原文地址:https://www.cnblogs.com/huiy/p/9492742.html

时间: 2024-10-04 10:32:40

springboot:mybatis配置多数据源的相关文章

SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页

SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页 **SpringBoot+Mybatis使用Pagehelper分页插件自动分页,非常好用,不用在自己去计算和组装了.全部自动实现. 话不多说,直接上代码: 第一步pom文件配置添加jar: <!-- mybatis的分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>

SpringBoot+Druid+Mybatis配置多数据源

我们在开发一个项目的时候,可能会遇到需要对多个数据库进行读写的需求,这时候就得在项目中配置多个数据源了.在Java项目的开发中,目前最常用的数据操作框架是 Mybatis,开发框架也都基本用上了SpringBoot.而Druid号称最好的数据库连接池,自然也是被广泛使用. 所以本文将演示一下,SpringBoot+Druid+Mybatis如何去配置多数据源.首先在IDEA中创建一个SpringBoot工程: 选择一些基本的包: 完成创建: pom.xml配置的依赖如下: <dependenci

springboot + mybatis配置分页插件

1:首先配置springboot +mybatis框架  参考:http://www.cnblogs.com/liyafei/p/7911549.html 2:创建配置类MybatisConfig,对分页插件进行配置.将mybatis-config.xml移动到classpath路径下. package com.liyafei.util.pagehelper; import java.util.Properties; import org.apache.ibatis.plugin.Interce

Mybatis配置多数据源

一. Spring配置多数据源 二. Spring配置数据源 三. MultipleDataSource的实现 1: package com.wbl.modal; 2:  3: import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 4:  5: /** 6: * Created with Simple_love 7: * Date: 2016/4/26. 8: * Time: 11:12 9: *

SpringBoot mybatis配置

首先pom.xml <!-- mybatis 配置 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <dependency> <

[转]SpringMVC+ Mybatis 配置多数据源 + 手动切换数据源

正确可行的解决方法:使用Spring提供的AbstractRoutingDataSource类来根据请求路由到不同的数据源.具体做法是先设置两个不同的dataSource代表不同的数据源,再建一个总的dynamicDataSource,根据不同的请求去设置dynamicDataSource.代码如下: 配置文件spring-mybatis.xml <!--统一的dataSource--> <bean id="dynamicDataSource" class="

【转】一次SpringMVC+ Mybatis 配置多数据源经历

需求 现在在维护的是学校的一款信息服务APP的后台,最近要开发一些新功能,其中一个就是加入学校电影院的在线购票.在线购票实际上已经有一套系统了,但是是外包给别人开发的,我们拿不到代码只能拿到数据库,并且也不一定能很好的兼容之前的代码,所以需要基于这个数据库来进行新的开发. 现在用的后台是SpringMVC+Mybatis+MySQL开发的,购票用的是SQL Server 2008(好古老的东西了),因为要用一套用户体系所以不可能再去单独为了这个功能弄一个系统出来,因此要在原项目中兼容这个数据库.

springboot+mybatis+Druid配置多数据源(mysql+postgre)

springboot+mybatis+Druid配置多数据源(mysql+postgre)引入pom依赖设置application多数据源config配置db1config配置(主数据库配置)db2config配置(其他数据库)事务处理mapper层 springboot+mybatis+Druid配置多数据源(mysql+postgre) 参考资料: 第八章 springboot + mybatis + 多数据源 springboot + mybatis + druid + 多数据源 spri

Spring Boot + MyBatis + Pagehelper 配置多数据源

前言: 本文为springboot结合mybatis配置多数据源,在项目当中很多情况是使用主从数据源来读写分离,还有就是操作多库,本文介绍如何一个项目同时使用2个数据源. 也希望大家带着思考去学习!博主是最近才学的配置写成博文分享心得和技巧,文中有不足的欢迎留言指正,谢谢! 思考: 1.如果从传统的单数据源转换为多数据源,以前使用boot只用导包写配置文件boot会帮我们自动配置,如果不用自动配置我们改怎么配呢? 2.怎么结合mybatis分页插件一起使用呢? .................