首頁 Java java教程 Springboot怎麼整合mybatis實現多資料來源配置

Springboot怎麼整合mybatis實現多資料來源配置

May 20, 2023 pm 03:42 PM
mybatis springboot

新建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就可以知道這兩個資料來源分別載入了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註解來指定目前資料來源下定義的實體和mapper的套件路徑,也注入了sqlSessionFactory和sqlSessionTemplate,透過@Qualifier註解指定了對應的資料來源,其名字對應在DataSourceConfiguration配置類別中的資料來源定義的函數名稱。

各個對資料來源對應路徑下的實體和mapper

@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
    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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
iBatis和MyBatis:哪個比較適合你? iBatis和MyBatis:哪個比較適合你? Feb 19, 2024 pm 04:38 PM

iBatis與MyBatis:你該選擇哪一個?簡介:隨著Java語言的快速發展,許多持久化框架也應運而生。 iBatis和MyBatis是兩個備受歡迎的持久化框架,它們都提供了一個簡單而高效的資料存取解決方案。本文將介紹iBatis和MyBatis的特點和優勢,並給出一些具體的程式碼範例,幫助你選擇合適的框架。 iBatis簡介:iBatis是一個開源的持久化框架

比較分析JPA和MyBatis的功能和性能 比較分析JPA和MyBatis的功能和性能 Feb 19, 2024 pm 05:43 PM

JPA和MyBatis:功能與效能比較分析引言:在Java開發中,持久化框架扮演著非常重要的角色。常見的持久化框架包括JPA(JavaPersistenceAPI)和MyBatis。本文將對這兩個框架的功能和效能進行比較分析,並提供具體的程式碼範例。一、功能對比:JPA:JPA是JavaEE的一部分,提供了一個物件導向的資料持久化解決方案。它透過註解或X

詳解MyBatis動態SQL標籤中的Set標籤功能 詳解MyBatis動態SQL標籤中的Set標籤功能 Feb 26, 2024 pm 07:48 PM

MyBatis動態SQL標籤解讀:Set標籤用法詳解MyBatis是一個優秀的持久層框架,它提供了豐富的動態SQL標籤,可以靈活地建構資料庫操作語句。其中,Set標籤是用來產生UPDATE語句中SET子句的標籤,在更新作業中非常常用。本文將詳細解讀MyBatis中Set標籤的用法,以及透過具體的程式碼範例來示範其功能。什麼是Set標籤Set標籤用於MyBati

實作MyBatis中批次刪除操作的多種方式 實作MyBatis中批次刪除操作的多種方式 Feb 19, 2024 pm 07:31 PM

MyBatis中實現批量刪除語句的幾種方式,需要具體程式碼範例近年來,由於資料量的不斷增加,批量操作成為了資料庫操作的一個重要環節之一。在實際開發中,我們經常需要批量刪除資料庫中的記錄。本文將重點介紹在MyBatis中實作批量刪除語句的幾種方式,並提供相應的程式碼範例。使用foreach標籤實作批量刪除MyBatis提供了foreach標籤,可以方便地遍歷一個集

MyBatis批次刪除語句的使用方法詳解 MyBatis批次刪除語句的使用方法詳解 Feb 20, 2024 am 08:31 AM

MyBatis批量刪除語句的使用方法詳解,需要具體程式碼範例引言:MyBatis是一款優秀的持久層框架,提供了豐富的SQL操作功能。在實際專案開發中,經常會遇到需要大量刪除資料的情況。本文將詳細介紹MyBatis批量刪除語句的使用方法,並附上具體的程式碼範例。使用場景:在資料庫中刪除大量資料時,逐條執行刪除語句效率低。此時,可以使用MyBatis的批次刪除功能

MyBatis快取機制詳解:一文讀懂快取儲存原理 MyBatis快取機制詳解:一文讀懂快取儲存原理 Feb 23, 2024 pm 04:09 PM

MyBatis快取機制詳解:一文讀懂快取儲存原理引言在使用MyBatis進行資料庫存取時,快取是一個非常重要的機制,能夠有效減少對資料庫的訪問,提高系統效能。本文將詳細介紹MyBatis的快取機制,包括快取的分類、儲存原理和具體的程式碼範例。一、快取的分類MyBatis的快取主要分為一級快取和二級快取兩種。一級緩存一級緩存是SqlSession級別的緩存,當在

iBatis與MyBatis的異同比較:主流ORM框架的對比 iBatis與MyBatis的異同比較:主流ORM框架的對比 Feb 19, 2024 pm 07:08 PM

iBatis和MyBatis是兩個主流的ORM(Object-RelationalMapping)框架,它們在設計和使用上有著許多相似之處,也存在一些細微的差別。本文將詳細比較iBatis和MyBatis的異同,並透過具體的程式碼範例來說明它們的特點。一、iBatis與MyBatis的歷史與背景iBatis是ApacheSoftwareFoundat

深入理解MyBatis中的批次Insert實作原理 深入理解MyBatis中的批次Insert實作原理 Feb 21, 2024 pm 04:42 PM

MyBatis是一款流行的Java持久層框架,廣泛應用於各種Java專案。其中,批次插入是常見的操作,可以有效提升資料庫操作的效能。本文將深入探討MyBatis中批量的Insert實作原理,並結合具體的程式碼範例進行詳細解析。 MyBatis中的批次Insert在MyBatis中,批量Insert操作通常使用動態SQL來實作。透過建構一條包含多個插入值的S

See all articles