首頁  >  文章  >  Java  >  Java Spring中同時存取多種不同資料庫的程式碼實例分享

Java Spring中同時存取多種不同資料庫的程式碼實例分享

黄舟
黄舟原創
2017-03-21 11:03:341532瀏覽

開發企業應用程式時我們常常遇到要同時存取多種不同資料庫的問題,有時是必須把資料歸檔到某種資料倉儲中,有時是要把資料變更推送到第三方資料庫。使用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