美文网首页
3、spring-boot整合myBaits(多数据源)

3、spring-boot整合myBaits(多数据源)

作者: KissGoodby | 来源:发表于2018-10-16 16:37 被阅读0次
    1、添加依赖
             <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
            </dependency>
    
    2、在application.properties添加相关配置
    spring.datasource1.driver-class-name = com.mysql.jdbc.Driver
    spring.datasource1.jdbc-url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
    spring.datasource1.username = root
    spring.datasource1.password = root
    
    
    spring.datasource2.driver-class-name = com.mysql.jdbc.Driver
    spring.datasource2.jdbc-url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
    spring.datasource2.username = root
    spring.datasource2.password = root
    

    在配置文件中配置多个数据源的连接地址

    3、配置数据来源
    1. 数据源1
    @Configuration
    @MapperScan(basePackages = "com.hui.wang.spring.boot.mapper.datasource1", sqlSessionTemplateRef = "sqlSessionTemplate1")
    public class DataSource1Config {
    
        @Bean(name = "dataSource1")
        @ConfigurationProperties(prefix = "spring.datasource1")
        @Primary
        public DataSource dataSource() {
            return DataSourceBuilder.create().build();
        }
    
        @Bean(name = "sqlSessionFactory1")
        @Primary
        public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource1") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            return bean.getObject();
        }
    
        @Bean(name = "transactionManager1")
        @Primary
        public DataSourceTransactionManager dataSourceTransactionManager (@Qualifier("dataSource1") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
    
        @Bean(name = "sqlSessionTemplate1")
        @Primary
        public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory) {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }
    
    1. 数据源2
    @Configuration
    @MapperScan(basePackages = "com.hui.wang.spring.boot.mapper.datasource2", sqlSessionTemplateRef = "sqlSessionTemplate2")
    public class DataSource2Config {
    
        @Bean(name = "dataSource2")
        @ConfigurationProperties(prefix = "spring.datasource2")
        public DataSource dataSource() {
            return DataSourceBuilder.create().build();
        }
    
        @Bean(name = "sqlSessionFactory2")
        public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource2") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            return bean.getObject();
        }
    
        @Bean(name = "transactionManager2")
        public DataSourceTransactionManager dataSourceTransactionManager (@Qualifier("dataSource2") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
    
        @Bean(name = "sqlSessionTemplate2")
        public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory) {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }
    

    springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对了你一切都不用管了,直接拿起来使用就行了。

    但是多个数据源的时候,需要将数据源的配置和mapper对应上,其中@MapperScan就是配置对应关系的,@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")这句话的意思就是指明了扫描dao层,并且给dao层注入指定的SqlSessionTemplate。所有@Bean都需要按照命名指定正确。
    @ ConfigurationProperties指定application.properties配置文件对应的数据源的key

    4、Mapper代码
    1. 数据源1的Mapper
    package com.hui.wang.spring.boot.mapper.datasource1;
    
    import java.util.List;
    
    import com.hui.wang.spring.boot.domain.UserEntity;
    import com.hui.wang.spring.boot.enums.UserSexEnum;
    import org.apache.ibatis.annotations.Delete;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Result;
    import org.apache.ibatis.annotations.Results;
    import org.apache.ibatis.annotations.Select;
    
    @Mapper
    public interface UserMapper1 {
    
        @Select("SELECT * FROM user")
        @Results({
                @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
                @Result(property = "nickName", column = "nick_name")
        })
        List<UserEntity> getAll();
    
        @Select("SELECT * FROM users WHERE id = #{id}")
        @Results({
                @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
                @Result(property = "nickName", column = "nick_name")
        })
        UserEntity getOne(Long id);
    
        @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
        void insert(UserEntity userEntity);
    
        @Delete("DELETE FROM users WHERE id =#{id}")
        void delete(Long id);
    }
    
    1. 数据源2的Mapper
    package com.hui.wang.spring.boot.mapper.datasource2;
    
    import java.util.List;
    
    import com.hui.wang.spring.boot.domain.UserEntity;
    import com.hui.wang.spring.boot.enums.UserSexEnum;
    import org.apache.ibatis.annotations.Delete;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Result;
    import org.apache.ibatis.annotations.Results;
    import org.apache.ibatis.annotations.Select;
    
    @Mapper
    public interface UserMapper2 {
    
        @Select("SELECT * FROM user")
        @Results({
                @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
                @Result(property = "nickName", column = "nick_name")
        })
        List<UserEntity> getAll();
    
        @Select("SELECT * FROM users WHERE id = #{id}")
        @Results({
                @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
                @Result(property = "nickName", column = "nick_name")
        })
        UserEntity getOne(Long id);
    
        @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
        void insert(UserEntity userEntity);
    
        @Delete("DELETE FROM users WHERE id =#{id}")
        void delete(Long id);
    
    }
    

    这样就配置好了多数据源的Mapper,直接在项目中使用对应的Mapper就行了

    相关文章

      网友评论

          本文标题:3、spring-boot整合myBaits(多数据源)

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