前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot 1.0 && 2.0 + Mybatis 多数据源配置与使用

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

作者头像
happyJared
发布2018-12-19 16:34:00
1.1K0
发布2018-12-19 16:34:00
举报
文章被收录于专栏:happyJaredhappyJared

环境说明

  • 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中定义如下信息:

代码语言:javascript
复制
spring:
  jpa:
    hibernate:
      # 多数据源下,该属性不生效,需要在配置中额外指定,这里仅表示普通定义
      ddl-auto: create-drop
    properties:
      hibernate:
        show_sql: true
        format_sql: true
        jdbc:
          lob:
            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

配置数据源

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

代码语言:javascript
复制
// 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 支持:

代码语言:javascript
复制
@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 支持:

代码语言:javascript
复制
@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

代码语言:javascript
复制
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Boy {

    private Integer id;

    private String name;

}
代码语言:javascript
复制
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

代码语言:javascript
复制
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Girl {

    private Integer id;

    private String name;

}
代码语言:javascript
复制
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();

}

单元测试

代码语言:javascript
复制
@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());

        girlMapper.insert(new Girl(1, "小红"));
        girlMapper.insert(new Girl(2, "小花"));
        Assert.assertEquals(2, girlMapper.findAll().size());
    }

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.11.24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 环境说明
  • 连接配置
  • 配置数据源
  • Mybatis 支持
  • 相关定义
  • 单元测试
相关产品与服务
云数据库 MySQL
腾讯云数据库 MySQL(TencentDB for MySQL)为用户提供安全可靠,性能卓越、易于维护的企业级云数据库服务。其具备6大企业级特性,包括企业级定制内核、企业级高可用、企业级高可靠、企业级安全、企业级扩展以及企业级智能运维。通过使用腾讯云数据库 MySQL,可实现分钟级别的数据库部署、弹性扩展以及全自动化的运维管理,不仅经济实惠,而且稳定可靠,易于运维。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档