mybatis 多数据源

 

1.定义多个数据源的mybatis配置

application.properties 

mybatis.mapper-locations=mappers/*.xml
mybatisLog.mapper-locations=mappersLog/*.xml

## datasource master #
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=
jdbc:mysql://localhost:3306/test1?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=466

## datasource log #
spring.datasourceLog.type=com.alibaba.druid.pool.DruidDataSource
spring.datasourceLog.driver-class-name=com.mysql.jdbc.Driver
spring.datasourceLog.url=
jdbc:mysql://localhost:3306/log?characterEncoding=UTF-8
spring.datasourceLog.username=root
spring.datasourceLog.password=466

 

 

2.定义多个数据源

@Configuration
public class DatasourceConfig {

    @Bean(destroyMethod =  "close", name = DataSources.MASTER_DB)
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create()
        .type(DruidDataSource.class)
        .build();
    }

    @Bean(destroyMethod =  "close", name = DataSources.LOG_DB)
    @ConfigurationProperties(prefix = "spring.datasourceLog")
    public DataSource dataSourceLog() {
        return DataSourceBuilder.create()
        .type(DruidDataSource.class)
        .build();
    }
}

 

3.分别配置多个数据源

@Configuration
@MapperScan(basePackages = {"com.example.mapper.orders"})
public class MybatisConfig {

    @Autowired
    @Qualifier(DataSources.MASTER_DB)
    private DataSource masterDB;

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "db.order")
    public SqlSessionFactoryBean sqlSessionFactoryBean() {
        SqlSessionFactoryBean sqlSessionFactoryBean;
        sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(masterDB);
        return sqlSessionFactoryBean;
    }
}

.

@Configuration
@MapperScan(basePackages = {"com.example.mapper.users"}
, sqlSessionFactoryRef = "logSqlSessionFactory")
public class MybatisLogConfig {

    @Autowired
    @Qualifier("user")
    private DataSource userSource;

    @Bean(name = "logSqlSessionFactory")
    @ConfigurationProperties(prefix = "db.user")
    public SqlSessionFactoryBean sqlSessionFactoryBean() {
        SqlSessionFactoryBean sqlSessionFactoryBean;
        sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(userSource);
        return sqlSessionFactoryBean;
    }
}

 

关键

  • 1)Configuration 扫描不同的前缀,取不同包下的sql对应的xml文件
  • 2)SqlSessionFactoryBean 实例化时,默认的额外添加了 @Primary注解
  • 3)MapperScan 扫描的不同的包,如果扫描相同的包也能做,但是还需要做额外的配置,可以自己尝试
  • 4)不同的数据源使用不同的SqlSessionFactoryBean实例

 

 

.

此条目发表在java分类目录。将固定链接加入收藏夹。