美文网首页springboot
Spring Boot 1.0 && 2.0 + Mybatis

Spring Boot 1.0 && 2.0 + Mybatis

作者: happyJared | 来源:发表于2019-12-30 09:13 被阅读0次

    环境说明

    • 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:
      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
    

    配置数据源

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

    // 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());
    
            girlMapper.insert(new Girl(1, "小红"));
            girlMapper.insert(new Girl(2, "小花"));
            Assert.assertEquals(2, girlMapper.findAll().size());
        }
    
    }
    

    示例源码

    文章已授权转载,原文链接:Spring Boot 1.0 && 2.0 + Mybatis 多数据源配置与使用

    相关文章

      网友评论

        本文标题:Spring Boot 1.0 && 2.0 + Mybatis

        本文链接:https://www.haomeiwen.com/subject/jdrvgctx.html