SpringBoot 配置多數據源(MyBatis版)

第一步:創建SpringBoot項目

Maven依賴:

<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
   <exclusions>
      <exclusion>
         <groupId>org.junit.vintage</groupId>
         <artifactId>junit-vintage-engine</artifactId>
      </exclusion>
   </exclusions>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-configuration-processor</artifactId>
   <optional>true</optional>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>8.0.20</version>
</dependency>
<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.4</version>
</dependency>
<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>2.0.4</version>
</dependency>
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.1.3</version>
</dependency>
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-autoconfigure</artifactId>
   <version>2.1.3</version>
</dependency>

在application.yml配置文件中新增兩個數據源

server:
    port: 80
    servlet:
        context-path: /mds
spring:
    datasource:
        test1:
            driverClassName: com.mysql.cj.jdbc.Driver
            jdbc-url: jdbc:mysql://localhost:3306/db_test?useSSL=false&serverTimezone=UTC&user=root&password=&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true
            password: root
            username: root
        test2:
            driverClassName: com.mysql.cj.jdbc.Driver
            jdbc-url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&user=root&password=&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true
            password: root
            username: root

第二步:創建Mapper

在包com.hc.test1.mapper下創建DeptMapper1.java

@Mapper
public interface DeptMapper1 {
    @Insert("insert into tb_dept(dname,loc) values(#{dname},#{loc})")
    void insert(Dept dept);
    @Select("select * from tb_dept")
    List<Dept> selectAllDept();
}

在包com.hc.test2.mapper下創建DeptMapper2.java

@Mapper
public interface DeptMapper2 {
    @Insert("insert into tb_dept(dname,loc) values(#{dname},#{loc})")
    void insert(Dept dept);
    @Select("select * from tb_dept")
    List<Dept> selectAllDept();
}

第三步:配置文件中指定數據源

application.ym中test1所對應的配置文件DataSource1Config

@Configuration // 註冊到springboot容器中
@MapperScan(basePackages = "com.hc.test1.mapper", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSource1Config {
    // 創建數據源
    @Bean(name = "test1DataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }
    // 創建會話工廠
    @Bean(name = "test1SqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(
	@Qualifier("test1DataSource") DataSource dataSource)throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        return factory.getObject();
    }
    // 創建模板
    @Bean(name = "test1SqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    //創建事物管理
    @Bean(name = "test1TransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource ds) {
        return new DataSourceTransactionManager(ds);
    }
}

application.ym中test2所對應的配置文件DataSource2Config

@Configuration // 註冊到springboot容器中
@MapperScan(basePackages = "com.hc.test2.mapper", sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSource2Config {
    //創建數據源
    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test2")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }
    //創建會話工廠
    @Bean(name = "test2SqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        return factory.getObject();
    }
    //創建模板
    @Bean(name = "test2SqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    //創建事務管理
    @Bean(name = "test2TransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource ds) {
        return new DataSourceTransactionManager(ds);
    }
}

第四步:測試代碼

DeptMapper1Test

@SpringBootTest
public class DeptMapper1Test {
    @Resource
    private DeptMapper1 deptMapper1;
    @Test
    public void insert() {
        Dept dept = new Dept(10, "aaa", "aaaaaaaa");
        deptMapper1.insert(dept);
        System.out.println(deptMapper1);
    }
    @Test
    public void selectAllDept() {
        List<Dept> depts = deptMapper1.selectAllDept();
        depts.forEach(System.out::println);
    }
}

DeptMapper2Test

@SpringBootTest
class DeptMapper2Test {
    @Resource
    private DeptMapper2 deptMapper2;
    @Test
    void insert() {
    }
    @Test
    void selectAllDept() {
        deptMapper2.selectAllDept().forEach(System.out::println);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章