架构师

您现在的位置是:首页 > 技术博客 > 数据库

数据库

Spring Boot集成MyBatis配置多数据源详细教程

架构师小跟班 2019-07-13数据库
一、工程创建申明一点本案例使用的springboot版本是1.5.6.RELEASE。首先需要创建springBoot项目,添加springBoot框架对MyBatis支持的相关依赖Jar:分别添加MyBatis、MySQL以及W

一、工程创建

申明一点本案例使用的springboot版本是1.5.6.RELEASE。首先需要创建springBoot项目,添加springBoot框架对MyBatis支持的相关依赖Jar:分别添加MyBatis、MySQL以及Web依赖以及Druid依赖,这里添加Druid依赖必须是Spring boot支持的Druid,不能使用传统的Druid。完整的依赖jar如下:

<dependencies>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.28</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.3</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.15</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

二、多数据源配置

接下来配置多数据源,首先在配置文件application.properties中配置2个数据库基本信息,然后配置两个DataSource即可,这里笔者把代码贴出来,并且附上解释说明信息。application.properties文件的配置:

server.port=7001
spring.application.name=springCloud-multiple-dataSources
spring.instance.instance-id=${spring.application.name}:${server.port}

## 数据源1的配置(此处***替换成自己数据库的连接串以及用户名和密码)
spring.datasource.wxdev.url= ****
spring.datasource.wxdev.username=****
spring.datasource.wxdev.password=****
spring.datasource.wxdev.driverClassName=com.mysql.jdbc.Driver
spring.datasource.wxdev.type=com.alibaba.druid.pool.DruidDataSource

## 数据源2的配置(此处***替换成自己数据库的连接串以及用户名和密码) 
spring.datasource.platform.url=***
spring.datasource.platform.username=****
spring.datasource.platform.password=****
spring.datasource.platform.driverClassName=com.mysql.jdbc.Driver
spring.datasource.platform.type=com.alibaba.druid.pool.DruidDataSource

logging.config=classpath:logback_spring.xml

## mybatis mapper文件配置
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.config-location=classpath:mybatis/mybatis-config.xml

然后再定义两个DataSource的配置类(分别对应上面的2个数据源),如下:
数据源1配置

@Configuration
@MapperScan(basePackages = "com.chenyun.cloud.mapper.wxdev",sqlSessionTemplateRef = "SqlSessionTemplate1")
public class DataSourceOneConfig {

    private static final String MAPPER_LOCATION = "classpath:mybatis/mapper/wxdev/*.xml";

    @Value("${spring.datasource.wxdev.url}")
    private String url;

    @Value("${spring.datasource.wxdev.username}")
    private String user;

    @Value("${spring.datasource.wxdev.password}")
    private String password;

    @Value("${spring.datasource.wxdev.driverClassName}")
    private String driverClass;

    @Bean
    @Primary
    public DataSource dataSourceOne() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "dataSourceOneTransactionManager")
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSourceOne());
    }

    @Bean(name = "SqlSessionFactory1")
    public SqlSessionFactory getSqlSessionFactory1(@Qualifier("dataSourceOne") DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

    @Bean(name = "SqlSessionTemplate1")
    public SqlSessionTemplate getSqlSessionTemplate1(
            @Qualifier("SqlSessionFactory1") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }        
}

数据源2配置

@Configuration
@MapperScan(basePackages = "com.chenyun.cloud.mapper.platform", sqlSessionTemplateRef = "SqlSessionTemplate2")
public class DataSourceTwoConfig {

    private static final String MAPPER_LOCATION = "classpath:mybatis/mapper/platform/*.xml";

    @Value("${spring.datasource.platform.url}")
    private String url;

    @Value("${spring.datasource.platform.username}")
    private String user;

    @Value("${spring.datasource.platform.password}")
    private String password;

    @Value("${spring.datasource.platform.driverClassName}")
    private String driverClass;

    @Bean(name = "dataSourceTwo")
    public DataSource dataSourceTwo() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "dataSourceOneTransactionManager")
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSourceTwo());
    }

    @Bean(name = "SqlSessionFactory2")
    public SqlSessionFactory getSqlSessionFactory2(@Qualifier("dataSourceTwo") DataSource dataSourceTwo)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSourceTwo);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

    @Bean(name = "SqlSessionTemplate2")
    public SqlSessionTemplate getSqlSessionTemplate2(
            @Qualifier("SqlSessionFactory2") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

上面这个数据源配置类说明:在配置类上面加注解@Configuration表示这是一个可以被spring容器扫描到的配置类,配置类中注解@MapperScan表示要扫描的包路径com.chenyun.cloud.mapper.platform,即该包下的Mapper接口将操作dataSourceTwo中的数据,对应的SqlSessionFactory和SqlSessionTemplate分别是sqlSessionFactory2和sqlSessionTemplate2,在配置类内部,分别提供SqlSessionFactory和SqlSessionTemplate即可。需要注意的是,多数据源配置必须指定哪个数据源是主数据源,需用注解@Primary标明,例如本案例数据源dataSourceOne上的注解。

现在MyBatis多数据源就配置好了,接下来只需要在com.chenyun.cloud.mapper.wxdev和com.chenyun.cloud.mapper.platform包中提供不同的Mapper接口以及在resources目录下面创建不同xml映射文件。

接下来,在Service中注入两个不同的Mapper接口,就可以操作不同的数据源,关于springBoot集成MyBatis多数据源案例就分享到这里,如有问题,扫码关注公众号,联系笔者微信。

文章评论