搜尋
首頁Javajava教程Java Spring中同時存取多種不同資料庫的程式碼實例分享

開發企業應用程式時我們常常遇到要同時存取多種不同資料庫的問題,有時是必須把資料歸檔到某種資料倉儲中,有時是要把資料變更推送到第三方資料庫。使用Spring框架時,使用單一資料庫是非常容易的,但如果要同時存取多個資料庫的話事件就變得複雜多了。

本文以在Spring框架下開發一個SpringMVC程式為例,示範了一種同時存取多種資料庫的方法,而且盡量簡化配置變更。

建立資料庫

建議你也同時搭好兩個資料庫來跟進我們的範例。本文中我們用了PostgreSQL和MySQL。

下面的腳本內容是在兩個資料庫中建立表格和插入資料的命令。

PostgreSQL

CREATE TABLE usermaster ( 
   id integer, 
   name character varying, 
   emailid character varying, 
   phoneno character varying(10), 
   location character varying
) 

INSERT INTO usermaster(id, name, emailid, phoneno, location)
VALUES (1, 'name_postgres', 'email@email.com', '1234567890', 'IN');

MySQL

CREATE TABLE `usermaster` (
   `id` int(11) NOT NULL, 
   `name` varchar(255) DEFAULT NULL, 
   `emailid` varchar(20) DEFAULT NULL, 
   `phoneno` varchar(20) DEFAULT NULL, 
   `location` varchar(20) DEFAULT NULL, 
   PRIMARY KEY (`id`) 
)

INSERT INTO `kode12`.`usermaster` 
  (`id`, `name`, `emailid`, `phoneno`, `location`)
VALUES
  ('1', 'name_mysql', 'test@tset.com', '9876543210', 'IN');

建構專案

我們用Spring Tool Suite (STS)來建立這個範例:

  • 點選File -> New -> Spring Starter Project。

  • 在對話方塊中輸入專案名稱、Maven座標、描述和套件資訊等,點選Next。

  • 在boot dependency中選擇Web,點選Next。

  • 點選Finish。 STS會自動依照專案依賴關係從Spring倉庫下載所需的內容。

創建完的項目如下圖所示:

#接下來我們仔細研究專案中的各個相關文件內容。

pom.xml

pom中包含了所有需要的依賴和外掛程式映射關係。

程式碼:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
    http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.aegis</groupId>
    <artifactId>MultipleDBConnect</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>MultipleDB</name>
    <description>MultipleDB with Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

解釋:

#下面詳細解釋各種依賴關係的細節:

  • spring-boot-starter -web:為Web開發和MVC提供支援。

  • spring-boot-starter-test:提供JUnit、Mockito等測試依賴。

  • spring-boot-starter-jdbc:提供JDBC支援。

  • postgresql:PostgreSQL資料庫的JDBC驅動程式。

  • mysql-connector-java:MySQL資料庫的JDBC驅動程式。

application.properties

#包含程式所需的所有設定資訊。在舊版的Spring中我們要透過多個XML檔案來提供這些設定資訊。

server.port=6060
spring.ds_post.url =jdbc:postgresql://localhost:5432/kode12
spring.ds_post.username =postgres
spring.ds_post.password =root
spring.ds_post.driverClassName=org.postgresql.Driver
spring.ds_mysql.url = jdbc:mysql://localhost:3306/kode12
spring.ds_mysql.username = root
spring.ds_mysql.password = root
spring.ds_mysql.driverClassName=com.mysql.jdbc.Driver

解釋:

「server.port=6060」宣告你的嵌入式伺服器啟動後會使用6060連接埠(port.server.port是Boot預設的標準連接埠)。

其他屬性中:

  • 以「spring.ds_*」為前綴的是使用者定義屬性。

  • 以「spring.ds_post.*」為前綴的是為PostgreSQL資料庫定義的屬性。

  • 以「spring.ds_mysql.*」為前綴的是為MySQL資料庫定義的屬性。

MultipleDbApplication.java

package com.aegis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public MultipleDbApplication {

    public static void main(String[] args) {
        SpringApplication.run(MultipleDbApplication.class, args);
    }
}

這個檔案包含了啟動我們的Boot程式的主函數。註解「@SpringBootApplication」是所有其他Spring註解和Java註解的組合,包括:

@Configuration
@EnableAutoConfiguration
@ComponentScan
@Target(value={TYPE})
@Retention(value=RUNTIME)
@Documented
@Inherited

其他註解:

@Configuration
@EnableAutoConfiguration
@ComponentScan

上述註解會讓容器透過這個類別來載入我們的配置。

MultipleDBConfig.java

package com.aegis.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class MultipleDBConfig {
    @Bean(name = "mysqlDb")
    @ConfigurationProperties(prefix = "spring.ds_mysql")
    public DataSource mysqlDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "mysqlJdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("mysqlDb") DataSource dsMySQL) {
        return new JdbcTemplate(dsMySQL);
    }

    @Bean(name = "postgresDb")
    @ConfigurationProperties(prefix = "spring.ds_post")
    public DataSource postgresDataSource() {
        return  DataSourceBuilder.create().build();
    }

    @Bean(name = "postgresJdbcTemplate")
    public JdbcTemplate postgresJdbcTemplate(@Qualifier("postgresDb") 
                                              
    DataSource dsPostgres) {
        return new JdbcTemplate(dsPostgres);
    }
}

#解釋:

這是一個加了註解的設定類,包含載入我們的PostgreSQL和MySQL資料庫配置的函數和註解。這也會負責為每一種資料庫建立JDBC模板類別。

下面我們來看這四個函數:

@Bean(name = "mysqlDb")
@ConfigurationProperties(prefix = "spring.ds_mysql")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create().build();
}

上面程式碼第一行建立了mysqlDb bean。
第二行幫助@Bean載入了所有有前綴spring.ds_mysql的屬性。
第四行建立並初始化了DataSource類,並建立了mysqlDb DataSource物件。

@Bean(name = "mysqlJdbcTemplate")
public JdbcTemplate jdbcTemplate(@Qualifier("mysqlDb") DataSource dsMySQL) {
     return new JdbcTemplate(dsMySQL);
}

第一行以mysqlJdbcTemplate為名建立了一個JdbcTemplate類型的新Bean。
第二行將第一行建立的DataSource類型新參數傳入函數,並以mysqlDB為qualifier。
第三行用DataSource物件初始化JdbcTemplate實例。

@Bean(name = "postgresDb")
@ConfigurationProperties(prefix = "spring.ds_post")
public DataSource postgresDataSource() {
   return  DataSourceBuilder.create().build();
}

第一行建立DataSource實例postgresDb。
第二行幫助@Bean載入所有以spring.ds_post為前綴的設定。
第四行建立並初始化DataSource實例postgresDb。

@Bean(name = "postgresJdbcTemplate")
public JdbcTemplate postgresJdbcTemplate(@Qualifier("postgresDb")
DataSource dsPostgres) {
  return new JdbcTemplate(dsPostgres);
}

第一行以postgresJdbcTemplate為名建立JdbcTemplate類型的新bean。
第二行接受DataSource類型的參數,並以postgresDb為qualifier。
第三行用DataSource物件初始化JdbcTemplate實例。

DemoController.java

package com.aegis.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @Autowired
    @Qualifier("postgresJdbcTemplate")
    private JdbcTemplate postgresTemplate;

    @Autowired
    @Qualifier("mysqlJdbcTemplate")
    private JdbcTemplate mysqlTemplate;

    @RequestMapping(value = "/getPGUser")
    public String getPGUser() {
        Map<String, Object> map = new HashMap<String, Object>();
        String query = " select * from usermaster";
        try {
            map = postgresTemplate.queryForMap(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "PostgreSQL Data: " + map.toString();
    }

    @RequestMapping(value = "/getMYUser")
    public String getMYUser() {
        Map<String, Object> map = new HashMap<String, Object>();
        String query = " select * from usermaster";
        try {
            map = mysqlTemplate.queryForMap(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "MySQL Data: " + map.toString();
    }
}

解釋:

@RestController類別註解顯示這個類別中定義的所有函數都被預設綁定到回應中。

上面代码段创建了一个JdbcTemplate实例。@Qualifier用于生成一个对应类型的模板。代码中提供的是postgresJdbcTemplate作为Qualifier参数,所以它会加载MultipleDBConfig实例的jdbcTemplate(…)函数创建的Bean。

这样Spring就会根据你的要求来调用合适的JDBC模板。在调用URL “/getPGUser”时Spring会用PostgreSQL模板,调用URL “/getMYUser”时Spring会用MySQL模板。

@Autowired
@Qualifier("postgresJdbcTemplate")
private JdbcTemplate postgresTemplate;

这里我们用queryForMap(String query)函数来使用JDBC模板从数据库中获取数据,queryForMap(…)返回一个map,以字段名为Key,Value为实际字段值。

演示

执行类MultipleDbApplication中的main (…)函数就可以看到演示效果。在你常用的浏览器中点击下面URL:

URL: http://localhost:6060/getMYUser

上面的URL会查询MySQL数据库并以字符串形式返回数据。

Url: http://localhost:6060/getPGUser

上面的URL会查询PostgreSQL数据库并以字符串形式返回数据。

以上是Java Spring中同時存取多種不同資料庫的程式碼實例分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?Mar 17, 2025 pm 05:46 PM

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?Mar 17, 2025 pm 05:45 PM

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?Mar 17, 2025 pm 05:44 PM

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?Mar 17, 2025 pm 05:43 PM

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Mar 17, 2025 pm 05:35 PM

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

記事本++7.3.1

記事本++7.3.1

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具