欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java同時(shí)配置多個(gè)數(shù)據(jù)庫(kù)的完整步驟

 更新時(shí)間:2025年09月14日 08:27:58   作者:廣煜永不掛科  
在當(dāng)今的數(shù)據(jù)驅(qū)動(dòng)時(shí)代,應(yīng)用程序往往需要連接多個(gè)數(shù)據(jù)庫(kù)以便獲取和處理數(shù)據(jù),這篇文章主要介紹了java同時(shí)配置多個(gè)數(shù)據(jù)庫(kù)的完整步驟,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

環(huán)境:springboot(沒有mybatis,有其實(shí)也無所謂。)

1、鏈接數(shù)據(jù)庫(kù)的配置

首先是,在只配置一個(gè)數(shù)據(jù)庫(kù),我們需要在springboot的application.properties進(jìn)行如下配置

# 數(shù)據(jù)源配置
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://目標(biāo)IP:1433;databaseName=ZCFW-SC;encrypt=false;trustServerCertificate=true
spring.datasource.username=用戶名
spring.datasource.password=密碼

當(dāng)運(yùn)行時(shí),springboot會(huì)以spring.datasource為根去尋找數(shù)據(jù)庫(kù)鏈接所需的地址,用戶名和密碼。因?yàn)橹挥幸粋€(gè)數(shù)據(jù)庫(kù),我們不需要為“連接配置”額外命名。

2、鏈接多個(gè)數(shù)據(jù)庫(kù)——命名

當(dāng)只有一個(gè)數(shù)據(jù)庫(kù),我們不需要為“連接配置”額外命名,而當(dāng)數(shù)據(jù)庫(kù)變多時(shí),我們就需要為不同的“連接配置”額外命名了。

好比是家里有個(gè)一個(gè)孩子,吃飯時(shí)只需要“孩兒,過來吃飯了”

但是有兩個(gè)孩子,就需要“大娃二娃過來吃飯了”

所以有一下:

# 數(shù)據(jù)源1配置
spring.datasource.db1.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.db1.jdbc-url=jdbc:sqlserver://目標(biāo)IP:1433;databaseName=ZCFW-SC;
spring.datasource.db1.username=sa
spring.datasource.db1.password=12345678
# 其他配置...

# 數(shù)據(jù)源2配置
spring.datasource.db2.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.db2.jdbc-url=jdbc:sqlserver://目標(biāo)IP:3306;databaseName=pdmvpdb;
spring.datasource.db2.username=newuser
spring.datasource.db2.password=123123
# 其他配置...

其中db1和db2就是我們?yōu)閰^(qū)分不同數(shù)據(jù)庫(kù)連接配置進(jìn)行的命名。

當(dāng)只連接一個(gè)數(shù)據(jù)庫(kù)的時(shí)候,我們寫的是“spring.datasource.url”其實(shí)他真正的寫法應(yīng)該是spring.datasource.*.url,其中的* 就是系統(tǒng)自動(dòng)給數(shù)據(jù)庫(kù)連接分配的默認(rèn)名,這個(gè)默認(rèn)名在我們需要鏈接多個(gè)數(shù)據(jù)庫(kù)時(shí)就不能用了,因?yàn)椴恢滥憬械恼l(shuí)。

3、鏈接多個(gè)數(shù)據(jù)庫(kù)——識(shí)別

我們知道db1和db2是我們?yōu)閰^(qū)分不同數(shù)據(jù)庫(kù)連接配置而進(jìn)行的命名,但是別人不知道。

就好像我們知道“大娃二娃”是我們的孩子,但是鄰居不知道哪個(gè)是大娃哪個(gè)是二娃,我們就需要和他們解釋。紅肚兜的是大娃,綠肚兜的時(shí)二娃。

所以還需要讓代碼在運(yùn)行時(shí)可以識(shí)別區(qū)分不同的數(shù)據(jù)庫(kù)連接。

我們需要一個(gè)java配置文件,來讓系統(tǒng)知道我們說的db1和db2是誰(shuí)。

①、命名

我們?yōu)閿?shù)據(jù)源命名的這個(gè)方法共分為三部分:

其中的 @ConfigurationProperties(prefix = "spring.datasource.db1") 是告訴程序,我們要給db1這個(gè)鏈接命名,

@Bean(name = "db1DataSource")還給db1起了一個(gè)大名db1DataSource,從此以后你叫db1DataSource,大家就都知道你要找db1這個(gè)數(shù)據(jù)庫(kù)了。

下邊的方法主體是告訴程序,我們的db1是一個(gè)數(shù)據(jù)庫(kù)連接,請(qǐng)以一個(gè)數(shù)據(jù)庫(kù)連接的標(biāo)準(zhǔn)對(duì)待他

    public DataSource firstDataSource() {
        return DataSourceBuilder.create().build();
    }

②、綁定JDBC

除此之外,我們還要綁定JDBC,然后用JDBC訪問數(shù)據(jù)庫(kù)

    // 綁定 db1 的 JdbcTemplate
    @Bean(name = "db1JdbcTemplate")
    public JdbcTemplate db1JdbcTemplate(
            @Qualifier("db1DataSource") DataSource dataSource) { // 通過 @Qualifier 指定數(shù)據(jù)源
        return new JdbcTemplate(dataSource);
    }

完整代碼如下:

package com.example.demo;

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.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class MultiDataSourceConfig {

    // 主數(shù)據(jù)源(必須指定@Primary,否則會(huì)沖突)
    @Primary
    @Bean(name = "db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db1") // 綁定第一個(gè)數(shù)據(jù)源的屬性
    public DataSource firstDataSource() {
        return DataSourceBuilder.create().build();
    }

    // 第二個(gè)數(shù)據(jù)源
    @Bean(name = "db2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db2") // 綁定第二個(gè)數(shù)據(jù)源的屬性
    public DataSource secondDataSource() {
        return DataSourceBuilder.create().build();
    }

    // 綁定 db1 的 JdbcTemplate
    @Bean(name = "db1JdbcTemplate")
    public JdbcTemplate db1JdbcTemplate(
            @Qualifier("db1DataSource") DataSource dataSource) { // 通過 @Qualifier 指定數(shù)據(jù)源
        return new JdbcTemplate(dataSource);
    }

    // 綁定 db2 的 JdbcTemplate
    @Bean(name = "db2JdbcTemplate")
    public JdbcTemplate db2JdbcTemplate(
            @Qualifier("db2DataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

4、鏈接多個(gè)數(shù)據(jù)庫(kù)——取消默認(rèn)

只是命名還沒用,此時(shí)如果你來到application.properties的頁(yè)面,你會(huì)發(fā)現(xiàn)提示無法解析配置屬性。這是當(dāng)然的,因?yàn)檎缥覀冎八f,系統(tǒng)會(huì)默認(rèn)給你的數(shù)據(jù)庫(kù)命名為*,所以你以為你寫的是spring.datasource.db1,其實(shí)在系統(tǒng)看來你寫的是spring.datasource.*.db1 現(xiàn)在你就要告訴系統(tǒng)不要自作主張給我的數(shù)據(jù)庫(kù)命名了。

找到你的主程序,大概率是 項(xiàng)目名稱+application,然后把@SpringBootApplication改成@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) 

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) // 排除默認(rèn)數(shù)據(jù)源自動(dòng)配置
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
		System.out.println("Ciallo~(∠?ω< )⌒★start  \n");
	}

}

然后問題就解決了。

5、使用

如下,我為我數(shù)據(jù)庫(kù)中一個(gè)名叫test的表寫了一個(gè)Model類和對(duì)應(yīng)的數(shù)據(jù)庫(kù)增刪改查類:

model類:

package com.example.sqlServerConnect.model;

public class testModel {
    // 自增主鍵(假設(shè) autonum 是自增列,插入時(shí)無需手動(dòng)賦值)
    private Integer autonum;
    private Integer id;        // 列名:ID
    private Integer fh;        // 列名:fh(非空)
    private Integer qishi;     // 列名:qishi(允許空)
    private Integer zhongzhi;  // 列名:zhongzhi(允許空)
    private Integer qishim;    // 列名:qishim(允許空)
    private Integer zhongzhim; // 列名:zhongzhim(允許空)
    private String xuhao;      // 列名:xuhao(nvarchar(50),允許空)
    private String miaoshu;    // 列名:miaoshu(varchar(MAX),允許空)
    private String juanhao;    // 列名:juanhao(varchar(50),允許空)
    private String jiluren;    // 列名:jiluren(nchar(10),允許空)
    private String tbbarcodeS; // 列名:tbbarcode_s(nvarchar(50),允許空)
    private String tbbarcodeE; // 列名:tbbarcode_e(nvarchar(50),允許空)
    private String zuofeizhonglei; // 列名:zuofeizhonglei(nvarchar(50),允許空)
    private String zhengfu;    // 列名:zhengfu(nchar(10),允許空)
    private Integer deleteLength; // 列名:DeleteLength(int,允許空)

    // --- autonum 的 Getter 和 Setter ---
    public Integer getAutonum() {
        return autonum;
    }

    public void setAutonum(Integer autonum) {
        this.autonum = autonum;
    }

    // --- id 的 Getter 和 Setter ---
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    // --- fh 的 Getter 和 Setter ---
    public Integer getFh() {
        return fh;
    }

    public void setFh(Integer fh) {
        this.fh = fh;
    }

    // --- qishi 的 Getter 和 Setter ---
    public Integer getQishi() {
        return qishi;
    }

    public void setQishi(Integer qishi) {
        this.qishi = qishi;
    }

    // --- zhongzhi 的 Getter 和 Setter ---
    public Integer getZhongzhi() {
        return zhongzhi;
    }

    public void setZhongzhi(Integer zhongzhi) {
        this.zhongzhi = zhongzhi;
    }

    // --- qishim 的 Getter 和 Setter ---
    public Integer getQishim() {
        return qishim;
    }

    public void setQishim(Integer qishim) {
        this.qishim = qishim;
    }
    public Integer getZhongzhim() {
        return zhongzhim;
    }
    public void setZhongzhim(Integer zhongzhim) {
        this.zhongzhim = zhongzhim;
    }
    public String getXuhao() {
        return xuhao;
    }
    public void setXuhao(String xuhao) {
        this.xuhao = xuhao;
    }
    public String getMiaoshu() {
        return miaoshu;
    }
    public void setMiaoshu(String miaoshu) {
        this.miaoshu = miaoshu;
    }
    public String getJuanhao() {
        return juanhao;
    }
    public void setJuanhao(String juanhao) {
        this.juanhao = juanhao;
    }
    public String getJiluren() {
        return jiluren;
    }
    public void setJiluren(String jiluren) {
        this.jiluren = jiluren;
    }
    public String getTbbarcodeS() {
        return tbbarcodeS;
    }
    public void setTbbarcodeS(String tbbarcodeS) {
        this.tbbarcodeS = tbbarcodeS;
    }
    public String getTbbarcodeE() {
        return tbbarcodeE;
    }
    public void setTbbarcodeE(String tbbarcodeE) {
        this.tbbarcodeE = tbbarcodeE;
    }
    public String getZuofeizhonglei() {
        return zuofeizhonglei;
    }
    public void setZuofeizhonglei(String zuofeizhonglei) {
        this.zuofeizhonglei = zuofeizhonglei;
    }
    public String getZhengfu() {
        return zhengfu;
    }
    public void setZhengfu(String zhengfu) {
        this.zhengfu = zhengfu;
    }
    public Integer getDeleteLength() {
        return deleteLength;
    }
    public void setDeleteLength(Integer deleteLength) {
        this.deleteLength = deleteLength;
    }
}

增刪改查類:

package com.example.sqlServerConnect.controller;

import com.example.sqlServerConnect.model.testModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class testController {

    // 注入 JdbcTemplate(多數(shù)據(jù)源場(chǎng)景需通過 @Qualifier 指定 Bean 名稱,如 "firstJdbcTemplate")
    @Autowired
    @Qualifier("db1JdbcTemplate") // 替換為實(shí)際配置的 JdbcTemplate Bean 名稱
    private JdbcTemplate jdbcTemplate;


    // 1. 插入數(shù)據(jù)(autonum 若為自增,無需傳入)
    public int insert(testModel entity) {
        String sql = "INSERT INTO test (ID, fh, qishi, zhongzhi, qishim, zhongzhim, xuhao, miaoshu, juanhao, jiluren, tbbarcode_s, tbbarcode_e, zuofeizhonglei, zhengfu, DeleteLength) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        return jdbcTemplate.update(sql,
                entity.getId(),
                entity.getFh(),
                entity.getQishi(),
                entity.getZhongzhi(),
                entity.getQishim(),
                entity.getZhongzhim(),
                entity.getXuhao(),
                entity.getMiaoshu(),
                entity.getJuanhao(),
                entity.getJiluren(),
                entity.getTbbarcodeS(),
                entity.getTbbarcodeE(),
                entity.getZuofeizhonglei(),
                entity.getZhengfu(),
                entity.getDeleteLength());
    }


    // 2. 根據(jù) autonum 刪除數(shù)據(jù)
    public int deleteByAutonum(Integer autonum) {
        String sql = "DELETE FROM test WHERE autonum = ?";
        return jdbcTemplate.update(sql, autonum);
    }


    // 3. 更新數(shù)據(jù)(根據(jù) autonum)
    public int update(testModel entity) {
        String sql = "UPDATE test SET ID=?, fh=?, qishi=?, zhongzhi=?, qishim=?, zhongzhim=?, xuhao=?, miaoshu=?, juanhao=?, jiluren=?, tbbarcode_s=?, tbbarcode_e=?, zuofeizhonglei=?, zhengfu=?, DeleteLength=? " +
                "WHERE autonum=?";
        return jdbcTemplate.update(sql,
                entity.getId(),
                entity.getFh(),
                entity.getQishi(),
                entity.getZhongzhi(),
                entity.getQishim(),
                entity.getZhongzhim(),
                entity.getXuhao(),
                entity.getMiaoshu(),
                entity.getJuanhao(),
                entity.getJiluren(),
                entity.getTbbarcodeS(),
                entity.getTbbarcodeE(),
                entity.getZuofeizhonglei(),
                entity.getZhengfu(),
                entity.getDeleteLength(),
                entity.getAutonum());
    }


    // 4. 根據(jù) autonum 查詢單條數(shù)據(jù)
    public testModel findByAutonum(Integer autonum) {
        String sql = "SELECT * FROM test WHERE autonum = ?";
        // BeanPropertyRowMapper 自動(dòng)將查詢結(jié)果映射為 test 對(duì)象(需列名與屬性名匹配,或通過別名適配)
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(testModel.class), autonum);
    }


    // 5. 查詢所有數(shù)據(jù)
    public List<testModel> findAll() {
        String sql = "SELECT * FROM test";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(testModel.class));
    }
}

注:報(bào)錯(cuò):db1JdbcTemplate為null

報(bào)錯(cuò)的同時(shí)也會(huì)提示:@Autowired提示:不建議使用字段注入

原因:字段注入存在一些潛在問題,Spring 官方和行業(yè)最佳實(shí)踐更推薦構(gòu)造器注入setter 注入。

字段注入:

    @Autowired
    @Qualifier("db1JdbcTemplate") // 替換為實(shí)際配置的 JdbcTemplate Bean 名稱
    private JdbcTemplate jdbcTemplate;

構(gòu)造函數(shù)注入:

    public JdbcTemplate jdbcTemplate;
    // 構(gòu)造器注入(推薦,避免 null 問題)
    @Autowired
    public Feigen821Controller(@Qualifier("db1JdbcTemplate") JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate; // 直接賦值,不會(huì)為 null
    }

Setter 注入(適合可選依賴):

就是利用get/set函數(shù)實(shí)現(xiàn)依賴的注入

    // Setter 注入
    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

三種注入方法比較:

字段注入并不推薦、構(gòu)造函數(shù)注入安全性可靠性最高、setter注入為手動(dòng)注入方法,可以自選依賴。

總結(jié)

到此這篇關(guān)于java同時(shí)配置多個(gè)數(shù)據(jù)庫(kù)的文章就介紹到這了,更多相關(guān)java同時(shí)配置多個(gè)數(shù)據(jù)庫(kù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springboot中redis正確的使用詳解

    springboot中redis正確的使用詳解

    本文主要介紹了springboot中redis正確的使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-04-04
  • Runtime.getRuntime().exec 路徑包含空格的解決

    Runtime.getRuntime().exec 路徑包含空格的解決

    這篇文章主要介紹了Runtime.getRuntime().exec 路徑包含空格的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • Mybatis遷移到Mybatis-Plus的實(shí)現(xiàn)方法

    Mybatis遷移到Mybatis-Plus的實(shí)現(xiàn)方法

    這篇文章主要介紹了Mybatis遷移到Mybatis-Plus的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • springboot集成springCloud中g(shù)ateway時(shí)啟動(dòng)報(bào)錯(cuò)的解決

    springboot集成springCloud中g(shù)ateway時(shí)啟動(dòng)報(bào)錯(cuò)的解決

    這篇文章主要介紹了springboot集成springCloud中g(shù)ateway時(shí)啟動(dòng)報(bào)錯(cuò)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java客戶端服務(wù)端上傳接收文件實(shí)現(xiàn)詳解

    Java客戶端服務(wù)端上傳接收文件實(shí)現(xiàn)詳解

    這篇文章主要介紹了Java客戶端服務(wù)端上傳接收文件實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07
  • SpringBoot Actuator跟蹤HTTP請(qǐng)求和響應(yīng)的方法

    SpringBoot Actuator跟蹤HTTP請(qǐng)求和響應(yīng)的方法

    Spring Boot Actuator 是 Spring Boot 提供的生產(chǎn)級(jí)監(jiān)控和管理模塊,旨在幫助開發(fā)者實(shí)時(shí)監(jiān)控應(yīng)用狀態(tài)、收集運(yùn)行時(shí)指標(biāo),并提供一系列管理端點(diǎn),本文給大家介紹了SpringBoot Actuator跟蹤HTTP請(qǐng)求和響應(yīng)的方法,需要的朋友可以參考下
    2025-08-08
  • SpringBoot實(shí)現(xiàn)自動(dòng)配置全過程

    SpringBoot實(shí)現(xiàn)自動(dòng)配置全過程

    SpringBoot通過自動(dòng)配置減少樣板代碼,基于條件注解和spring.factories篩選加載配置類,結(jié)合外部配置和自定義模塊實(shí)現(xiàn)靈活配置,提供調(diào)試工具排查問題
    2025-08-08
  • 深入了解SparkSQL中數(shù)據(jù)的加載與保存

    深入了解SparkSQL中數(shù)據(jù)的加載與保存

    這篇文章主要為大家詳細(xì)介紹了SparkSQL中數(shù)據(jù)的加載與保存的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解下
    2023-11-11
  • MybatisX-Generator自動(dòng)代碼生成插件教程

    MybatisX-Generator自動(dòng)代碼生成插件教程

    這篇文章主要介紹了MybatisX-Generator自動(dòng)代碼生成插件教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04

最新評(píng)論