SpringBoot Mybatis项目中的多数据源支持

1.概述

有时项目里里需要抽取不同系统中的数据源,需要访问不同的数据库,本文介绍在Springboot+Mybatis项目中如何支持多数据源操作。

有需要的同学可以下载 示例代码

项目结构如下:

2.建数据源

首先,我们建两个测试库 test1 test2,分别建两个表,分别添加一些测试数据

CREATE TABLE `groupidinfo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `groupId` varchar(255) DEFAULT NULL,
  `version` varchar(255) DEFAULT NULL,
  `cluster` varchar(255) DEFAULT NULL,
  `timeout` int(11) DEFAULT NULL,
  `retries` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

3.添加POM依赖

  pom文件中添加项目依赖

 <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

4.配置文件

  application.properties 文件中添加数据库连接配制

spring.datasource.db1.jdbc-url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.db1.username=root
spring.datasource.db1.password=123456
spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.db2.jdbc-url=jdbc:mysql://127.0.0.1:3306/test1
spring.datasource.db2.username=root
spring.datasource.db2.password=123456
spring.datasource.db2.driverClassName=com.mysql.jdbc.Driver

 5.配置文件

分别建立Db1DataSourceConfig,Db2DataSourceConfig,通过使用@MapperScan分别的两个数据源指定要扫描的Mapper类的包的路径,配置MapperLocations路径

@Configuration
@MapperScan(basePackages = "com.glory.study.dao.mapper.db1", sqlSessionTemplateRef  = "db1SqlSessionTemplate")
public class Db1DataSourceConfig {
    @Bean(name = "db1Data")
    @ConfigurationProperties(prefix = "spring.datasource.db1") // application.properteis中对应属性的前缀
    @Primary
    public DataSource Db1DataSourceConfig() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "db1SqlSessionFactory")
    @Primary
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1Data") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
       // bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/db1/*.xml"));
        return bean.getObject();
    }

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

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

 

6.添加数据库对应的实体类,并编写 Mybatis Mapper

直接写sql方式

@Mapper
@Repository
public interface GroupIdInfoDb1Mapper {
    
    @Select(" SELECT * FROM groupIdInfo WHERE id=#{id} limit 0,1;")
    GroupIdInfo findById1(@Param("id") Integer id);
    
}

Mapper XML方式

@Mapper
@Repository
public interface GroupIdInfoDb2Mapper {

    GroupIdInfo findById2(@Param("id") Integer id);

}
<mapper namespace="com.glory.study.dao.mapper.db2.GroupIdInfoDb2Mapper">

    <select id="findById2" resultType="com.glory.study.model.GroupIdInfo">
       SELECT * FROM groupIdInfo WHERE id=#{id} limit 0,1;
    </select>

</mapper>

7.编写调用Service

@Service
public class GroupIdInfoService {

    //数据源1
    @Autowired
    private GroupIdInfoDb1Mapper groupIdInfoDb1Mapper;
    //数据源2
    @Autowired
    private GroupIdInfoDb2Mapper groupIdInfoDb2Mapper;

    public GroupIdInfo findById1(Integer id) throws Exception {
        return groupIdInfoDb1Mapper.findById1(id);
    }

    public GroupIdInfo findById2(Integer id) throws Exception {
        return groupIdInfoDb2Mapper.findById2(id);
    }
}

8.编写调用Controller

@RestController
public class DubboConfigController {

    @Autowired
    private GroupIdInfoService groupIdInfoService;

    @RequestMapping("/dubboConfig1/{id}")
    GroupIdInfo finddubboConfig1(@PathVariable("id") Integer id) throws Exception{
       return groupIdInfoService.findById1(id);
    }

    @RequestMapping("/dubboConfig2/{id}")
    GroupIdInfo finddubboConfig2(@PathVariable("id") Integer id) throws Exception{
        return groupIdInfoService.findById2(id);
    }
    
}

9.启动测试,成功

参考

http://www.ityouknow.com/springboot/2016/11/25/spring-boot-multi-mybatis.html

原文地址:https://www.cnblogs.com/Guroer/p/10158929.html