精通SpringBoot——第十三篇:整合Mybatis多数据源

  1. 云栖社区>
  2. 博客>
  3. 正文

精通SpringBoot——第十三篇:整合Mybatis多数据源

developlee 2018-09-19 11:58:49 浏览1778

久违了,最近度过了一段倦怠期,这段时间干什么都没有动力,拖延症复发。好在我回来了.... ——From me .
进入今天的主题——在Spring Boot 项目中整合mybatis多数据源,其实很简单,其实并不难。
整体项目结构以及数据源配置application.yml:
image

看代码吧.

第一个数据源配置(作为主数据源)

/**
 * @author Lensen
 * @desc
 * @since 2018/9/19 10:22
 */
@Configuration
@MapperScan(basePackages = PrimaryDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {
    static final String PACKAGE = "com.developlee.multipartmybatisdatasource.dao.primary";
    static final String MAPPER_LOCATION = "classpath:mapper/primary/*.xml";
    @Value("${primary.datasource.url}")
    private String url;

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

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

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

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

    @Bean(name = "primaryTransactionManager")
    @Primary
    public DataSourceTransactionManager primaryTransactionManager() {
        return new DataSourceTransactionManager(primaryDataSource());
    }

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

第二个数据源配置



/**
 * @author Lensen
 * @desc
 * @since 2018/9/19 10:22
 */
@Configuration
@MapperScan(basePackages = SecondaryDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class SecondaryDataSourceConfig {
    static final String PACKAGE = "com.developlee.multipartmybatisdatasource.dao.secondary";
    static final String MAPPER_LOCATION = "classpath:mapper/secondary/*.xml";
    @Value("${secondary.datasource.url}")
    private String url;

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

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

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

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

    @Bean(name = "secondaryTransactionManager")
    public DataSourceTransactionManager secondaryTransactionManager() {
        return new DataSourceTransactionManager(secondaryDataSource());
    }

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

}

其他业务逻辑代码就不贴了,代码可在我的github上找到。文章末尾有地址。

application.yml


## primary 数据源配置
primary:
  datasource:
    url: jdbc:mysql://localhost:3306/javashop?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456
    driverClassName: com.mysql.jdbc.Driver

## secondary 数据源配置
secondary:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456
    driverClassName: com.mysql.jdbc.Driver

pom.xml

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

测试:


@RunWith(SpringRunner.class)
@SpringBootTest
public class MultipartMybatisDatasourceApplicationTests {

    @Autowired
    UserServiceImpl userService;
    @Autowired
    HomeServiceImpl homeService;
    @Test
    public void contextLoads() {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(1L);
        userEntity.setName("Lensen");
        userEntity.setMobile("13738718660");
        HomeEntity homeEntity = new HomeEntity();
        homeEntity.setId(1L);
        homeEntity.setUserId(1L);
        homeEntity.setCity("杭州");
        homeEntity.setTown("西湖区");

         userService.saveUser(userEntity);
         homeService.saveHome(homeEntity);

         userService.getUserById(1L);
         homeService.getHomeByUserId(1L);
    }

}

image

代码可以在我的github.com中找到。

That's All。 关注我的公众号,也不一定会更新文章。hahah~~
image