Java Spring中同時訪問多種不同資料庫
開發企業應用時我們常常遇到要同時訪問多種不同資料庫的問題,有時是必須把數據歸檔到某種數據倉庫中,有時是要把數據變更推送到第三方資料庫中。使用Spring框架時,使用單一資料庫是非常容易的,但如果要同時訪問多個資料庫的話事件就變得複雜多了。
本文以在Spring框架下開發一個SpringMVC程序為例,示範了一種同時訪問多種資料庫的方法,而且盡量地簡化配置改動。
搭建資料庫
建議你也同時搭好兩個資料庫來跟進我們的示例。本文中我們用了PostgreSQL和MySQL。
下面的腳本內容是在兩個資料庫中建表和插入數據的命令。
PostgreSQL
MySQL
搭建項目
我們用Spring Tool Suite (STS)來構建這個例子:
點擊File -> New -> Spring Starter Project。
在對話框中輸入項目名、Maven坐標、描述和包信息等,點擊Next。
在boot dependency中選擇Web,點擊Next。
點擊Finish。STS會自動按照項目依賴關係從Spring倉庫中下載所需要的內容。
創建完的項目如下圖所示:
接下來我們仔細研究一下項目中的各個相關文件內容。
pom.xml
pom中包含了所有需要的依賴和插件映射關係。
代碼:
4.0.0com.aegisMultipleDBConnect0.0.1-SNAPSHOTjarMultipleDBMultipleDB with Spring Bootorg.springframework.bootspring-boot-starter-parent1.3.5.RELEASEUTF-81.8org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-starter-jdbcorg.postgresqlpostgresqlmysqlmysql-connector-java5.1.38org.springframework.bootspring-boot-maven-plugin
解釋:
下面詳細解釋各種依賴關係的細節:
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 =postgresspring.ds_post.password =rootspring.ds_post.driverClassName=org.postgresql.Driverspring.ds_mysql.url = jdbc:mysql://localhost:3306/kode12spring.ds_mysql.username = rootspring.ds_mysql.password = rootspring.ds_mysql.driverClassName=com.mysql.jdbc.Driver
解釋:
其他屬性中:
以「spring.ds_*」為前綴的是用戶定義屬性。
以「spring.ds_post.*」為前綴的是為PostgreSQL資料庫定義的屬性。
以「spring.ds_mysql.*」為前綴的是為MySQL資料庫定義的屬性。
MultipleDbApplication.java
packagecom.aegis;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublicMultipleDbApplication {publicstaticvoidmain(String[] args){ SpringApplication.run(MultipleDbApplication.class, args); }}
這個文件包含了啟動我們的Boot程序的主函數。註解「@SpringBootApplication」是所有其他Spring註解和Java註解的組合,包括:
@Configuration@EnableAutoConfiguration@ComponentScan@Target(value=)@Retention(value=RUNTIME)@Documented@Inherited
其他註解:
@Configuration@EnableAutoConfiguration@ComponentScan
上述註解會讓容器通過這個類來載入我們的配置。
MultipleDBConfig.java
packagecom.aegis.config;importjavax.sql.DataSource;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Primary;importorg.springframework.jdbc.core.JdbcTemplate;@Configurationpublic class MultipleDBConfig { @Bean(name="mysqlDb") @ConfigurationProperties(prefix ="spring.ds_mysql") public DataSource mysqlDataSource() {returnDataSourceBuilder.create().build(); } @Bean(name="mysqlJdbcTemplate") public JdbcTemplate jdbcTemplate(@Qualifier("mysqlDb") DataSource dsMySQL) {returnnewJdbcTemplate(dsMySQL); } @Bean(name="postgresDb") @ConfigurationProperties(prefix ="spring.ds_post") public DataSource postgresDataSource() {returnDataSourceBuilder.create().build(); } @Bean(name="postgresJdbcTemplate") public JdbcTemplate postgresJdbcTemplate(@Qualifier("postgresDb") DataSource dsPostgres) {returnnewJdbcTemplate(dsPostgres); }}
解釋:
這是加了註解的配置類,包含載入我們的PostgreSQL和MySQL資料庫配置的函數和註解。這也會負責為每一種資料庫創建JDBC模板類。
下面我們看一下這四個函數:
@Bean(name ="mysqlDb")@ConfigurationProperties(prefix ="spring.ds_mysql")publicDataSourcemysqlDataSource(){returnDataSourceBuilder.create().build();}
上面代碼第一行創建了mysqlDb bean。
第二行幫助@Bean載入了所有有前綴spring.ds_mysql的屬性。
第四行創建並初始化了DataSource類,並創建了mysqlDb DataSource對象。
@Bean(name ="mysqlJdbcTemplate")publicJdbcTemplatejdbcTemplate(@Qualifier("mysqlDb")DataSource dsMySQL){returnnewJdbcTemplate(dsMySQL);}
第一行以mysqlJdbcTemplate為名創建了一個JdbcTemplate類型的新Bean。
第二行將第一行中創建的DataSource類型新參數傳入函數,並以mysqlDB為qualifier。
第三行用DataSource對象初始化JdbcTemplate實例。
@Bean(name ="postgresDb")@ConfigurationProperties(prefix ="spring.ds_post")publicDataSourcepostgresDataSource(){returnDataSourceBuilder.create().build();}
第一行創建DataSource實例postgresDb。
第二行幫助@Bean載入所有以spring.ds_post為前綴的配置。
第四行創建並初始化DataSource實例postgresDb。
@Bean(name ="postgresJdbcTemplate")publicJdbcTemplatepostgresJdbcTemplate(@Qualifier("postgresDb")DataSource dsPostgres){returnnewJdbcTemplate(dsPostgres);}
第一行以postgresJdbcTemplate為名創建JdbcTemplate類型的新bean。
第二行接受DataSource類型的參數,並以postgresDb為qualifier。
第三行用DataSource對象初始化JdbcTemplate實例。
DemoController.java
package com.aegis.controller;importjava.util.HashMap;importjava.util.Map;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.jdbc.core.JdbcTemplate;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RestControllerpublicclassDemoController{ @Autowired@Qualifier("postgresJdbcTemplate")privateJdbcTemplatepostgresTemplate; @Autowired@Qualifier("mysqlJdbcTemplate")privateJdbcTemplatemysqlTemplate; @RequestMapping(value ="/getPGUser")publicStringgetPGUser() {Mapmap= newHashMap();Stringquery =" select * from usermaster";try{map= postgresTemplate.queryForMap(query); }catch(Exceptione) { e.printStackTrace(); }return"PostgreSQL Data: "+map.toString(); } @RequestMapping(value ="/getMYUser")publicStringgetMYUser() {Mapmap= newHashMap();Stringquery =" select * from usermaster";try{map= mysqlTemplate.queryForMap(query); }catch(Exceptione) { 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")privateJdbcTemplate postgresTemplate;
這裡我們用queryForMap(String query)函數來使用JDBC模板從資料庫中獲取數據,queryForMap(…)返回一個map,以欄位名為Key,Value為實際欄位值。
演示
URL: http://localhost:6060/getMYUser
上面的URL會查詢MySQL資料庫並以字元串形式返回數據。
Url: http://localhost:6060/getPGUser
上面的URL會查詢PostgreSQL資料庫並以字元串形式返回數據。
關於作者
Aaron Jacobson是個經驗豐富的Java Web程序員,在外包與諮詢公司Technoligent擔任Java開發程序員10年以上。他的主要貢獻包括Java、Python、Asp.Net和手機應用等一系列Web解決方案。可以通過Twitter @Techno_Ligent或Facebook @TechnoLigent聯繫他。


※深入淺出 SOA 思想
※程序員面試題
※一個獨立開發者總結的App 迭代設計思路
※簡單粗暴地理解 JS 原型鏈
※JVM 初探:內存分配、GC 原理與垃圾收集器
TAG:程序源 |
※Servlet 資料庫訪問
※增量同步mysql資料庫信息到ElasticSearch
※管理vRealize Automation的vPostgres資料庫
※Oracle 資料庫中enq:TX-index contention等待時間淺析
※Intel Tiger Lake處理器出現在UserBenchmark資料庫中
※資料庫系統概念中table/view/schema/index的關係
※mybatis使用load data local infile實現導入數據到mysql資料庫
※springboot項目中使用原生jdbc連接MySQL資料庫
※SpringBoot使用資料庫
※Oracle資料庫定時器Job
※Gson+pulltorefer+資料庫+httpurlconnection+非同步(更新)
※Zero Day Initiative披露了Windows JET資料庫0Day漏洞
※Learning Memory Access Patterns,資料庫+機器學習探索
※Python Flask,資料庫,SQLAlchemy,模型類的定義,資料庫添加
※python web開發-flask連接sqlite資料庫
※通過 Docker 實現在 Linux 容器中運行 Microsoft SQL Server 資料庫
※SpringBoot整合MyBatis,MySql之從前台頁面到資料庫的小Demo
※Galaxy Note 9現身Geekbench資料庫
※雲資料庫TencentDforMemcached
※雲資料庫TencentDforSQLServer