ホームページ  >  記事  >  Java  >  Springboot は mybatis をどのように統合してマルチデータ ソース構成を実装しますか?

Springboot は mybatis をどのように統合してマルチデータ ソース構成を実装しますか?

WBOY
WBOY転載
2023-05-20 15:42:06852ブラウズ

新しい springboot プロジェクトを作成し、Web、mysql、mybatis の依存関係を導入する

		<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.2.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

application.properties で複数のデータ ソースを構成する

##spring.datasource.primary.jdbc-url= jdbc :mysql://localhost:3306/ds0

spring.datasource.primary.username=root
spring.datasource.primary.password=root
spring.datasource.primary.driver-class-name= com .mysql.cj.jdbc.Driver

spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/ds1

spring.datasource.secondary.username=root
spring.datasource.secondary.password=root
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver

複数のデータ ソース構成と単一のデータソース構成の違いは、さまざまなデータ ソースを区別するために、spring.datasource の後に追加のデータ ソース名primary/Secondaryがあることです。

データ ソースの初期化

複数のデータ ソースをロードするための新しい構成クラスを作成します。データソースが初期化されました。

@Configuration
public class DataSourceConfiguration {
    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}

@ConfigurationProperties を通じて、これら 2 つのデータ ソースがそれぞれ spring.datasource.primary.* と spring.datasource.secondary.* の構成をロードしたことがわかります。データ ソースが明示的に指定されていない場合は、@Primary アノテーションでマークされたプライマリ データ ソースが使用されます。

mybatis 構成

@Configuration
@MapperScan(
        basePackages = "com*.primary",
        sqlSessionFactoryRef = "sqlSessionFactoryPrimary",
        sqlSessionTemplateRef = "sqlSessionTemplatePrimary")
public class PrimaryConfig {
    private DataSource primaryDataSource;
    public PrimaryConfig(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
        this.primaryDataSource = primaryDataSource;
    }
    @Bean
    public SqlSessionFactory sqlSessionFactoryPrimary() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(primaryDataSource);
        return bean.getObject();
    }
    @Bean
    public SqlSessionTemplate sqlSessionTemplatePrimary() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryPrimary());
    }
}
@Configuration
@MapperScan(
        basePackages = "com.*.secondary",
        sqlSessionFactoryRef = "sqlSessionFactorySecondary",
        sqlSessionTemplateRef = "sqlSessionTemplateSecondary")
public class SecondaryConfig {
    private DataSource secondaryDataSource;
    public SecondaryConfig(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
        this.secondaryDataSource = secondaryDataSource;
    }
    @Bean
    public SqlSessionFactory sqlSessionFactorySecondary() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(secondaryDataSource);
        return bean.getObject();
    }
    @Bean
    public SqlSessionTemplate sqlSessionTemplateSecondary() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactorySecondary());
    }
}

@MapperScan アノテーションは、現在のデータ ソースで定義されたエンティティとマッパー パッケージのパスを指定するために構成クラスで使用されます。また、指定された sqlSessionFactory と sqlSessionTemplate も挿入されます。 @Qualifier アノテーション経由 対応するデータ ソース。その名前は、DataSourceConfiguration 構成クラスのデータ ソースによって定義された関数名に対応します。

データ ソースの各ペアの対応するパスにあるエンティティとマッパー

@Data
@NoArgsConstructor
public class UserPrimary {
    private Long id;
    private String user_name;
    private Integer age;
    public UserPrimary(String name, Integer age) {
        this.user_name = name;
        this.age = age;
    }
}
public interface UserMapperPrimary {
    @Select("SELECT * FROM USER_0 WHERE USER_NAME = #{name}")
    UserPrimary findByName(@Param("name") String name);
    @Insert("INSERT INTO USER_0 (USER_NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);
    @Delete("DELETE FROM USER_0")
    int deleteAll();
}
@Data
@NoArgsConstructor
public class UserSecondary {
    private Long id;
    private String user_name;
    private Integer age;
    public UserSecondary(String name, Integer age) {
        this.user_name = name;
        this.age = age;
    }
}
public interface UserMapperSecondary {
    @Select("SELECT * FROM USER_1 WHERE USER_NAME = #{name}")
    UserSecondary findByName(@Param("name") String name);
    @Insert("INSERT INTO USER_1 (USER_NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);
    @Delete("DELETE FROM USER_1")
    int deleteAll();
}

Test

	@Test
    public void test() {
        // 往Primary数据源插入一条数据
        userMapperPrimary.insert("caocao", 20);
        // 从Primary数据源查询刚才插入的数据,配置正确就可以查询到
        UserPrimary userPrimary = userMapperPrimary.findByName("caocao");
        Assert.assertEquals(20, userPrimary.getAge().intValue());
        // 从Secondary数据源查询刚才插入的数据,配置正确应该是查询不到的
        UserSecondary userSecondary = userMapperSecondary.findByName("caocao");
        Assert.assertNull(userSecondary);
        // 往Secondary数据源插入一条数据
        userMapperSecondary.insert("sunquan", 21);
        // 从Primary数据源查询刚才插入的数据,配置正确应该是查询不到的
        userPrimary = userMapperPrimary.findByName("sunquan");
        Assert.assertNull(userPrimary);
        // 从Secondary数据源查询刚才插入的数据,配置正确就可以查询到
        userSecondary = userMapperSecondary.findByName("sunquan");
        Assert.assertEquals(21, userSecondary.getAge().intValue());
    }

以上がSpringboot は mybatis をどのように統合してマルチデータ ソース構成を実装しますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。