相关文章推荐
讲道义的凉面  ·  中南海保镖,许正阳和杨倩儿没有在一起是多少人 ...·  6 月前    · 
年轻有为的热带鱼  ·  百度百科召开学术委员会首期研讨会,以权威知识 ...·  10 月前    · 
鬼畜的山羊  ·  招生问答-武汉纺织大学是几本?录取分数线是多少?·  1 年前    · 
八块腹肌的砖头  ·  联系我们| 客户帮助及支持中心- 汇丰新加坡·  1 年前    · 
难过的大熊猫  ·  体重管理师_体重管理师岗位能力证书介绍_报考 ...·  1 年前    · 
小百科  ›  Spring Boot 1.0 && 2.0 + Mybatis 多数据源配置与换用-腾讯云开发者社区-腾讯云
boot mybatis spring多数据源
满身肌肉的高山
1 年前
作者头像
happyJared
0 篇文章

Spring Boot 1.0 && 2.0 + Mybatis 多数据源配置与使用

前往专栏
腾讯云
开发者社区
文档 意见反馈 控制台
首页
学习
活动
专区
工具
TVP
文章/答案/技术大牛
发布
首页
学习
活动
专区
工具
TVP
返回腾讯云官网
社区首页 > 专栏 > happyJared > Spring Boot 1.0 && 2.0 + Mybatis 多数据源配置与使用

Spring Boot 1.0 && 2.0 + Mybatis 多数据源配置与使用

作者头像
happyJared
发布 于 2018-12-19 16:34:00
823 0
发布 于 2018-12-19 16:34:00
举报

环境说明

  • Spring Boot 1.5.17.RELEASE 或 Spring Boot 2.1.0.RELEASE
  • MySQL v5.6.19
  • PostgreSQL v10.4

无特殊说明,以下所说的环境均指 Spring Boot 2.1.0.RELEASE ,如果使用的是 Spring Boot 1.5.17.RELEASE 这个版本,只需要调整下面有做说明的几处地方

连接配置

在 application.yml 中定义如下信息:

spring:
    hibernate:
      # 多数据源下,该属性不生效,需要在配置中额外指定,这里仅表示普通定义
      ddl-auto: create-drop
    properties:
      hibernate:
        show_sql: true
        format_sql: true
        jdbc:
            non_contextual_creation: true
    open-in-view: false
  # 定义不同数据源的连接信息
  datasource:
    hikari:
      mysql:
        # Spring Boot 1.0+ 版本:使用spring.datasource.url
        # Spring Boot 2.0+ 版本:使用spring.datasource.hikari.jdbc-url
        jdbc-url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
        username: root
        password: root
        # Spring Boot 1.0+ 版本:使用com.mysql.jdbc.Driver
        # Spring Boot 2.0+ 版本:使用com.mysql.cj.jdbc.Driver
        driver-class-name: com.mysql.cj.jdbc.Driver
      postgres:
        jdbc-url: jdbc:postgresql://localhost:5432/postgres
        username: postgres
        password: postgres
        driver-class-name: org.postgresql.Driver

配置数据源

根据上面定义的配置信息,配置这两个数据源:

// Spring Boot 1.0+ ,DataSourceBuilder所在包位置为:org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder
// Spring Boot 2.0+ ,DataSourceBuilder所在包位置为:org.springframework.boot.jdbc.DataSourceBuilder
@Configuration
public class DataSourceConfig {
    @Primary
    @Bean
    @ConfigurationProperties("spring.datasource.hikari.mysql")
    public DataSource mysqlDataSource() {
        return DataSourceBuilder.create().build();
    @Bean
    @ConfigurationProperties("spring.datasource.hikari.postgres")
    public DataSource postgresDataSource() {
        return DataSourceBuilder.create().build();
}

Mybatis 支持

添加 mysql 对应数据源的 Mybatis 支持:

@Configuration
@MapperScan(
        // 数据层所在包位置
        basePackages = "cn.mariojd.springboot.multiple.datasource.mybatis.mysql.mapper",
        sqlSessionTemplateRef = "mybatisMysqlSqlSessionTemplate")
public class MybatisMysqlDataSourceConfig {
    @Resource
    @Qualifier("mysqlDataSource")
    private DataSource dataSource;
    @Bean
    @Primary
    public SqlSessionFactory mybatisMysqlSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        // 如果是xml形式,需要在此处指定mapper位置
        // factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mysql/mapper/*.xml"));
        return factoryBean.getObject();
    @Bean
    @Primary
    public DataSourceTransactionManager mybatisMysqlTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    @Bean
    @Primary
    public SqlSessionTemplate mybatisMysqlSqlSessionTemplate(@Qualifier("mybatisMysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
}

添加 postgres 对应数据源的 Mybatis 支持:

@Configuration
@MapperScan(
        // 数据层所在包位置
        basePackages = "cn.mariojd.springboot.multiple.datasource.mybatis.postgres.mapper",
        sqlSessionTemplateRef = "mybatisPostgresSqlSessionTemplate")
public class MybatisPostgresDataSourceConfig {
    @Resource
    @Qualifier("postgresDataSource")
    private DataSource dataSource;
    @Bean
    public SqlSessionFactory mybatisPostgresSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        // 如果是xml形式,需要在此处指定mapper位置
        // factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/postgres/mapper/*.xml"));
        return factoryBean.getObject();
    @Bean
    public DataSourceTransactionManager mybatisPostgresTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    @Bean
    public SqlSessionTemplate mybatisPostgresSqlSessionTemplate(@Qualifier("mybatisPostgresSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
}

相关定义

mysql 对应的数据源配置中,定义了实体 Boy 和对应的数据层接口 BoyMapper :

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Boy {
    private Integer id;
    private String name;
}
public interface BoyMapper {
    @Insert("INSERT INTO boy(id,name) VALUES(#{boy.id},#{boy.name})")
    @Options(useGeneratedKeys = true, keyProperty = "boy.id")
    int insert(@Param("boy") Boy boy);
    @Select("SELECT id,name FROM boy")
    @Results({
            @Result(property = "id", column = "id", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
            @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR),
    List<Boy> findAll();
}

postgres 对应的数据源配置中,定义了实体 Girl 和对应的数据层接口 GirlMapper :

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Girl {
    private Integer id;
    private String name;
}
public interface GirlMapper {
    @Insert("INSERT INTO girl(id,name) VALUES(#{girl.id},#{girl.name})")
    @Options(useGeneratedKeys = true, keyProperty = "girl.id")
    int insert(@Param("girl") Girl girl);
    @Select("SELECT id,name FROM girl")
    @Results({
            @Result(property = "id", column = "id", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
            @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR),
    List<Girl> findAll();
}

单元测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootMybatisMultipleDataSourceTest {
    @Resource
    private BoyMapper boyMapper;
    @Resource
    private GirlMapper girlMapper;
    @Test
    public void test() {
        boyMapper.insert(new Boy(1, "大肖"));
        boyMapper.insert(new Boy(2, "大熊"));
        Assert.assertEquals(2, boyMapper.findAll().size());
 
推荐文章
讲道义的凉面  ·  中南海保镖,许正阳和杨倩儿没有在一起是多少人心痛的遗憾_手机 ...
6 月前
年轻有为的热带鱼  ·  百度百科召开学术委员会首期研讨会,以权威知识打造普惠大众窗口 ...
10 月前
鬼畜的山羊  ·  招生问答-武汉纺织大学是几本?录取分数线是多少?
1 年前
八块腹肌的砖头  ·  联系我们| 客户帮助及支持中心- 汇丰新加坡
1 年前
难过的大熊猫  ·  体重管理师_体重管理师岗位能力证书介绍_报考_培训-文化科教培训网
1 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
小百科 - 百科知识指南
© 2024 ~ 沪ICP备11025650号