springbootを使って多データソースの配置を教えます。


一、倉庫建設表
1.1データベースdb 1とデータベースdb 2の作成
在这里插入图片描述
在这里插入图片描述
1.2データベースdb 1に表db 1を作成する
在这里插入图片描述

CREATE TABLE `db1` (
  `id` int unsigned zerofill NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `age` int unsigned zerofill DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
1.3データベースdb 2に表db 2を作成する
在这里插入图片描述

CREATE TABLE `db2` (
  `id` int unsigned zerofill NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `age` int unsigned zerofill DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
二、スプリングブックの作成項目
2.1 pom.xml導入依存

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </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>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
2.2 appication.ymlファイルを作成する(2.3の2つを選択して構成するので、この方法をおすすめします。)

server:
  port: 8080 #     
spring:
  datasource:
    db1: #    1
      jdbc-url: jdbc:mysql://localhost:3306/db1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver
    db2: #    2
      jdbc-url: jdbc:mysql://localhost:3306/db2?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver
2.3 appication.propertiesファイルを作成する(2.2と2のいずれかを選択して構成する)

server.port=8080

      spring.datasource.db1.url=jdbc:mysql://localhost:3306/db1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
      spring.datasource.db1.username=root
      spring.datasource.db1.password=root
      spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driver

      spring.datasource.db2.url=jdbc:mysql://localhost:3306/db2?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
      spring.datasource.db2.username=root
      spring.datasource.db2.password=root
      spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver
2.4 mapperファイルを作成する
個人的にはmapperに包んでファイルの名前を勝手に付けています。
コードは勝手に書いて、テストしただけです。
在这里插入图片描述

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;

/**
 * @Author if
 * @Description: What is it
 * @Date 2021-05-20    09:52
 */
@Mapper
public interface Db1Mapper {
    @Insert("insert into db1(name,age) values('if',18)")
    int add();
}

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;

/**
 * @Author if
 * @Description: What is it
 * @Date 2021-05-20    09:52
 */
@Mapper
public interface Db2Mapper {
    @Insert("insert into db2(name,age) values('fi',81)")
    int add();
}
2.5 configプロファイルを作成する
私は個人的にはconfigのカバンの下に置いています。ファイルの名前は自由です。
在这里插入图片描述

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;

/**
 * @Author if
 * @Description:               
 * @Date 2021-05-20    09:56
 */
@Configuration
@MapperScan(basePackages = "com.ifyyf.study.mapper.db1", sqlSessionFactoryRef = "db1SqlSessionFactory")
public class Db1DataSourceConfig {
    @Bean("db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db1") //  application.yml              
    public DataSource getDb1DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean("db1SqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // mapper xml           ,     :no statement (        mapper xml ,namespace           )
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/db1/*.xml"));
        return bean.getObject();
    }

    @Bean("db1SqlSessionTemplate")
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}


import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;

/**
 * @Author if
 * @Description:               
 * @Date 2021-05-20    09:56
 */
@Configuration
@MapperScan(basePackages = "com.ifyyf.study.mapper.db2", sqlSessionFactoryRef = "db2SqlSessionFactory")
public class Db2DataSourceConfig {
    @Bean("db2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db2") //  application.yml              
    public DataSource getDb2DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean("db2SqlSessionFactory")
    public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // mapper xml           ,     :no statement (        mapper xml ,namespace           )
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/db2/*.xml"));
        return bean.getObject();
    }

    @Bean("db2SqlSessionTemplate")
    public SqlSessionTemplate db2SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
三、テストコードの運行
3.1試験クラスのテストコード
springboot項目でテストクラスを行います。

import com.ifyyf.study.mapper.db1.Db1Mapper;
import com.ifyyf.study.mapper.db2.Db2Mapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;

@SpringBootTest
class StudyApplicationTests {
    @Resource
    private Db1Mapper db1Mapper;
    @Resource
    private Db2Mapper db2Mapper;
    @Test
    void contextLoads() {
        System.out.println(db1Mapper.add());
        System.out.println(db2Mapper.add());
    }
}
3.2運転結果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
以上で、springbootを使って多データソースを配置することについての記事を紹介します。もっと関連するspringbootは多データソースの内容を配置しています。私たちの以前の文章を検索したり、次の関連記事を見たりしてください。これからもよろしくお願いします。