溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java Spring中怎么同時訪問多種不同數據庫

發布時間:2021-08-17 22:02:16 來源:億速云 閱讀:503 作者:chen 欄目:編程語言

這篇文章主要介紹“Java Spring中怎么同時訪問多種不同數據庫”,在日常操作中,相信很多人在Java Spring中怎么同時訪問多種不同數據庫問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”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倉庫中下載所需要的內容。

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

Java Spring中怎么同時訪問多種不同數據庫Java 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=6060spring.ds_post.url =jdbc:postgresql://localhost:5432/kode12spring.ds_post.username =postgres spring.ds_post.password =root spring.ds_post.driverClassName=org.postgresql.Driverspring.ds_mysql.url = jdbc:mysql://localhost:3306/kode12spring.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;@SpringBootApplicationpublic 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;  @Configurationpublic 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;  @RestControllerpublic 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(&hellip;)函數創建的Bean。

這樣Spring就會根據你的要求來調用合適的JDBC模板。在調用URL “/getPGUser”時Spring會用PostgreSQL模板,調用URL “/getMYUser”時Spring會用MySQL模板。

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

這里我們用queryForMap(String query)函數來使用JDBC模板從數據庫中獲取數據,queryForMap(&hellip;)返回一個map,以字段名為Key,Value為實際字段值。

演示

執行類MultipleDbApplication中的main (&hellip;)函數就可以看到演示效果。在你常用的瀏覽器中點擊下面URL:

URL: http://localhost:6060/getMYUser

上面的URL會查詢MySQL數據庫并以字符串形式返回數據。

Java Spring中怎么同時訪問多種不同數據庫

Url: http://localhost:6060/getPGUser

上面的URL會查詢PostgreSQL數據庫并以字符串形式返回數據。

Java Spring中怎么同時訪問多種不同數據庫

到此,關于“Java Spring中怎么同時訪問多種不同數據庫”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女