自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Java Spring中同時(shí)訪問多種不同數(shù)據(jù)庫

開發(fā) 后端
本文以在Spring框架下開發(fā)一個(gè)SpringMVC程序?yàn)槔?,示范了一種同時(shí)訪問多種數(shù)據(jù)庫的方法,而且盡量地簡(jiǎn)化配置改動(dòng)。

開發(fā)企業(yè)應(yīng)用時(shí)我們常常遇到要同時(shí)訪問多種不同數(shù)據(jù)庫的問題,有時(shí)是必須把數(shù)據(jù)歸檔到某種數(shù)據(jù)倉庫中,有時(shí)是要把數(shù)據(jù)變更推送到第三方數(shù)據(jù)庫中。使用Spring框架時(shí),使用單一數(shù)據(jù)庫是非常容易的,但如果要同時(shí)訪問多個(gè)數(shù)據(jù)庫的話事件就變得復(fù)雜多了。

本文以在Spring框架下開發(fā)一個(gè)SpringMVC程序?yàn)槔?,示范了一種同時(shí)訪問多種數(shù)據(jù)庫的方法,而且盡量地簡(jiǎn)化配置改動(dòng)。

搭建數(shù)據(jù)庫

建議你也同時(shí)搭好兩個(gè)數(shù)據(jù)庫來跟進(jìn)我們的示例。本文中我們用了PostgreSQL和MySQL。

下面的腳本內(nèi)容是在兩個(gè)數(shù)據(jù)庫中建表和插入數(shù)據(jù)的命令。

PostgreSQL

  1. CREATE TABLE usermaster (  
  2.    id integer,  
  3.    name character varying,  
  4.    emailid character varying,  
  5.    phoneno character varying(10),  
  6.    location character varying)  
  7.  
  8. INSERT INTO usermaster(id, name, emailid, phoneno, location)VALUES (1, 'name_postgres''email@email.com''1234567890''IN');  

MySQL

  1. CREATE TABLE `usermaster` (   `id` int(11) NOT NULL,  
  2.    `namevarchar(255) DEFAULT NULL,  
  3.    `emailid` varchar(20) DEFAULT NULL,  
  4.    `phoneno` varchar(20) DEFAULT NULL,  
  5.    `location` varchar(20) DEFAULT NULL,  
  6.    PRIMARY KEY (`id`)  
  7. )INSERT INTO `kode12`.`usermaster`  
  8.   (`id`, `name`, `emailid`, `phoneno`, `location`)VALUES 
  9.   ('1''name_mysql''test@tset.com''9876543210''IN');  

搭建項(xiàng)目

我們用Spring Tool Suite (STS)來構(gòu)建這個(gè)例子:

點(diǎn)擊File -> New -> Spring Starter Project。

在對(duì)話框中輸入項(xiàng)目名、Maven坐標(biāo)、描述和包信息等,點(diǎn)擊Next。

在boot dependency中選擇Web,點(diǎn)擊Next。

點(diǎn)擊Finish。STS會(huì)自動(dòng)按照項(xiàng)目依賴關(guān)系從Spring倉庫中下載所需要的內(nèi)容。

創(chuàng)建完的項(xiàng)目如下圖所示:

 [[191743]] 

 

接下來我們仔細(xì)研究一下項(xiàng)目中的各個(gè)相關(guān)文件內(nèi)容。

pom.xml

pom中包含了所有需要的依賴和插件映射關(guān)系。

代碼:

  1. <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  
  4.     http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
  5.     <modelVersion>4.0.0</modelVersion> 
  6.  
  7.     <groupId>com.aegis</groupId> 
  8.     <artifactId>MultipleDBConnect</artifactId> 
  9.     <version>0.0.1-SNAPSHOT</version> 
  10.     <packaging>jar</packaging> 
  11.  
  12.     <name>MultipleDB</name
  13.     <description>MultipleDB with Spring Boot</description> 
  14.  
  15.     <parent> 
  16.         <groupId>org.springframework.boot</groupId> 
  17.         <artifactId>spring-boot-starter-parent</artifactId> 
  18.         <version>1.3.5.RELEASE</version> 
  19.         <relativePath /> 
  20.     </parent> 
  21.  
  22.     <properties> 
  23.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
  24.         <java.version>1.8</java.version> 
  25.     </properties> 
  26.  
  27.     <dependencies> 
  28.         <dependency> 
  29.             <groupId>org.springframework.boot</groupId> 
  30.             <artifactId>spring-boot-starter-web</artifactId> 
  31.         </dependency> 
  32.  
  33.         <dependency> 
  34.             <groupId>org.springframework.boot</groupId> 
  35.             <artifactId>spring-boot-starter-test</artifactId> 
  36.             <scope>test</scope> 
  37.         </dependency> 
  38.  
  39.         <dependency> 
  40.             <groupId>org.springframework.boot</groupId> 
  41.             <artifactId>spring-boot-starter-jdbc</artifactId> 
  42.         </dependency> 
  43.  
  44.         <dependency> 
  45.             <groupId>org.postgresql</groupId> 
  46.             <artifactId>postgresql</artifactId> 
  47.         </dependency> 
  48.  
  49.         <dependency> 
  50.             <groupId>mysql</groupId> 
  51.             <artifactId>mysql-connector-java</artifactId> 
  52.             <version>5.1.38</version> 
  53.         </dependency> 
  54.     </dependencies> 
  55.  
  56.     <build> 
  57.         <plugins> 
  58.             <plugin> 
  59.                 <groupId>org.springframework.boot</groupId> 
  60.                 <artifactId>spring-boot-maven-plugin</artifactId> 
  61.             </plugin> 
  62.         </plugins> 
  63.     </build></project>  

解釋:

下面詳細(xì)解釋各種依賴關(guān)系的細(xì)節(jié):

spring-boot-starter-web:為Web開發(fā)和MVC提供支持。

spring-boot-starter-test:提供JUnit、Mockito等測(cè)試依賴。

spring-boot-starter-jdbc:提供JDBC支持。

postgresql:PostgreSQL數(shù)據(jù)庫的JDBC驅(qū)動(dòng)。

mysql-connector-java:MySQL數(shù)據(jù)庫的JDBC驅(qū)動(dòng)。

application.properties

包含程序需要的所有配置信息。在舊版的Spring中我們要通過多個(gè)XML文件來提供這些配置信息。

  1. server.port=6060spring.ds_post.url =jdbc:postgresql://localhost:5432/kode12spring.ds_post.username =postgres 
  2. spring.ds_post.password =root 
  3. spring.ds_post.driverClassName=org.postgresql.Driverspring.ds_mysql.url = jdbc:mysql://localhost:3306/kode12spring.ds_mysql.username = root 
  4. spring.ds_mysql.password = root 
  5. spring.ds_mysql.driverClassName=com.mysql.jdbc.Driver  

解釋:

“server.port=6060”聲明你的嵌入式服務(wù)器啟動(dòng)后會(huì)使用6060端口(port.server.port是Boot默認(rèn)的標(biāo)準(zhǔn)端口)。

其他屬性中:

以“spring.ds_*”為前綴的是用戶定義屬性。

以“spring.ds_post.*”為前綴的是為PostgreSQL數(shù)據(jù)庫定義的屬性。

以“spring.ds_mysql.*”為前綴的是為MySQL數(shù)據(jù)庫定義的屬性。

MultipleDbApplication.java

  1. package com.aegis;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic MultipleDbApplication {    public static void main(String[] args) { 
  2.         SpringApplication.run(MultipleDbApplication.class, args); 
  3.     } 

這個(gè)文件包含了啟動(dòng)我們的Boot程序的主函數(shù)。注解“@SpringBootApplication”是所有其他Spring注解和Java注解的組合,包括:

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

其他注解:

  1. @Configuration@EnableAutoConfiguration@ComponentScan 

上述注解會(huì)讓容器通過這個(gè)類來加載我們的配置。

MultipleDBConfig.java

  1. 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; 
  2.  
  3. @Configurationpublic class MultipleDBConfig { 
  4.     @Bean(name = "mysqlDb"
  5.     @ConfigurationProperties(prefix = "spring.ds_mysql"
  6.     public DataSource mysqlDataSource() {        return DataSourceBuilder.create().build(); 
  7.     } 
  8.  
  9.     @Bean(name = "mysqlJdbcTemplate"
  10.     public JdbcTemplate jdbcTemplate(@Qualifier("mysqlDb") DataSource dsMySQL) {        return new JdbcTemplate(dsMySQL); 
  11.     } 
  12.  
  13.     @Bean(name = "postgresDb"
  14.     @ConfigurationProperties(prefix = "spring.ds_post"
  15.     public DataSource postgresDataSource() {        return  DataSourceBuilder.create().build(); 
  16.     } 
  17.  
  18.     @Bean(name = "postgresJdbcTemplate"
  19.     public JdbcTemplate postgresJdbcTemplate(@Qualifier("postgresDb")  
  20.                                               DataSource dsPostgres) {        return new JdbcTemplate(dsPostgres); 
  21.     } 

 解釋:

這是加了注解的配置類,包含加載我們的PostgreSQL和MySQL數(shù)據(jù)庫配置的函數(shù)和注解。這也會(huì)負(fù)責(zé)為每一種數(shù)據(jù)庫創(chuàng)建JDBC模板類。

下面我們看一下這四個(gè)函數(shù):

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

上面代碼***行創(chuàng)建了mysqlDb bean。

第二行幫助@Bean加載了所有有前綴spring.ds_mysql的屬性。

第四行創(chuàng)建并初始化了DataSource類,并創(chuàng)建了mysqlDb DataSource對(duì)象。

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

***行以mysqlJdbcTemplate為名創(chuàng)建了一個(gè)JdbcTemplate類型的新Bean。

第二行將***行中創(chuàng)建的DataSource類型新參數(shù)傳入函數(shù),并以mysqlDB為qualifier。

第三行用DataSource對(duì)象初始化JdbcTemplate實(shí)例。

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

***行創(chuàng)建DataSource實(shí)例postgresDb。

第二行幫助@Bean加載所有以spring.ds_post為前綴的配置。

第四行創(chuàng)建并初始化DataSource實(shí)例postgresDb。

  1. @Bean(name = "postgresJdbcTemplate")public JdbcTemplate postgresJdbcTemplate(@Qualifier("postgresDb"
  2.  
  3. DataSource dsPostgres) { return new JdbcTemplate(dsPostgres); 
  4.  

 

***行以postgresJdbcTemplate為名創(chuàng)建JdbcTemplate類型的新bean。

第二行接受DataSource類型的參數(shù),并以postgresDb為qualifier。

第三行用DataSource對(duì)象初始化JdbcTemplate實(shí)例。

DemoController.java

  1. 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; 
  2.  
  3. @RestControllerpublic class DemoController { 
  4.  
  5.     @Autowired 
  6.     @Qualifier("postgresJdbcTemplate")    private JdbcTemplate postgresTemplate; 
  7.  
  8.     @Autowired 
  9.     @Qualifier("mysqlJdbcTemplate")    private JdbcTemplate mysqlTemplate; 
  10.  
  11.     @RequestMapping(value = "/getPGUser")    public String getPGUser() {        Map<String, Object> map = new HashMap<String, Object>();        String query = " select * from usermaster";        try {            map = postgresTemplate.queryForMap(query); 
  12.         } catch (Exception e) { 
  13.             e.printStackTrace(); 
  14.         }        return "PostgreSQL Data: " + map.toString(); 
  15.     } 
  16.  
  17.     @RequestMapping(value = "/getMYUser")    public String getMYUser() {        Map<String, Object> map = new HashMap<String, Object>();        String query = " select * from usermaster";        try {            map = mysqlTemplate.queryForMap(query); 
  18.         } catch (Exception e) { 
  19.             e.printStackTrace(); 
  20.         }        return "MySQL Data: " + map.toString(); 
  21.     } 

解釋:

@RestController類注解表明這個(gè)類中定義的所有函數(shù)都被默認(rèn)綁定到響應(yīng)中。

上面代碼段創(chuàng)建了一個(gè)JdbcTemplate實(shí)例。@Qualifier用于生成一個(gè)對(duì)應(yīng)類型的模板。代碼中提供的是postgresJdbcTemplate作為Qualifier參數(shù),所以它會(huì)加載MultipleDBConfig實(shí)例的jdbcTemplate(…)函數(shù)創(chuàng)建的Bean。

這樣Spring就會(huì)根據(jù)你的要求來調(diào)用合適的JDBC模板。在調(diào)用URL “/getPGUser”時(shí)Spring會(huì)用PostgreSQL模板,調(diào)用URL “/getMYUser”時(shí)Spring會(huì)用MySQL模板。

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

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

演示

執(zhí)行類MultipleDbApplication中的main (…)函數(shù)就可以看到演示效果。在你常用的瀏覽器中點(diǎn)擊下面URL:

URL: http://localhost:6060/getMYUser

上面的URL會(huì)查詢MySQL數(shù)據(jù)庫并以字符串形式返回?cái)?shù)據(jù)。

 

Url: http://localhost:6060/getPGUser

上面的URL會(huì)查詢PostgreSQL數(shù)據(jù)庫并以字符串形式返回?cái)?shù)據(jù)。

 

關(guān)于作者

Aaron Jacobson是個(gè)經(jīng)驗(yàn)豐富的Java Web程序員,在外包與咨詢公司Technoligent擔(dān)任Java開發(fā)程序員10年以上。他的主要貢獻(xiàn)包括Java、Python、Asp.Net和手機(jī)應(yīng)用等一系列Web解決方案??梢酝ㄟ^Twitter @Techno_Ligent或Facebook @TechnoLigent聯(lián)系他。 

責(zé)任編輯:龐桂玉 來源: 程序源
相關(guān)推薦

2011-03-03 11:07:57

Spring數(shù)據(jù)庫訪問ORM

2011-01-21 11:12:01

Spring

2011-03-07 17:35:09

JavaACCESS數(shù)據(jù)庫

2011-08-04 15:55:25

SQL Server數(shù)

2011-03-17 15:59:37

c#數(shù)據(jù)庫

2020-07-17 07:27:17

數(shù)據(jù)庫即服務(wù)DBaaS

2023-09-01 10:26:44

數(shù)據(jù)庫Oracle

2017-05-25 10:23:13

數(shù)據(jù)a表b表

2010-04-20 14:32:49

Oracle LABE

2009-03-31 11:08:26

B-Tree索引數(shù)據(jù)庫

2009-07-02 09:00:25

JDBC設(shè)計(jì)JSP訪問數(shù)據(jù)庫

2011-07-14 16:55:36

Java遠(yuǎn)程訪問Domino數(shù)據(jù)庫

2010-09-09 15:13:33

SQL更新數(shù)據(jù)

2009-09-15 10:02:44

Linq to SQL

2011-03-16 17:26:22

動(dòng)態(tài)數(shù)據(jù)庫

2013-11-26 09:47:47

ORM

2010-05-20 14:52:42

MySQL數(shù)據(jù)庫

2009-07-02 09:35:02

hibernate訪問

2011-08-04 13:07:59

數(shù)據(jù)庫查詢TOP子句

2019-08-14 07:59:15

SQLite數(shù)據(jù)庫SQL
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)