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資料庫並以字串形式返回資料。
關於作者
Aaron Jacobson是個經驗豐富的Java Web程式設計師,在外包與諮詢公司Technoligent擔任Java開發程式設計師10年以上。他的主要貢獻包括Java、Python、Asp.Net和手機應用等一系列Web解決方案。可以通過Twitter @Techno_Ligent或Facebook @TechnoLigent聯絡他。
相關文章
- 使用PowerBuilder同時訪問多個資料庫UI資料庫
- 多個系統同時訪問和操作同一資料庫,可否使用hibernate資料庫
- spring-data-mongodb多資料庫訪問實現SpringMongoDB資料庫
- Spring框架訪問資料庫的兩種方式的小案例Spring框架資料庫
- 訪問資料庫的幾種方法資料庫
- Oracle資料鏈+同義詞+訪問遠端資料庫Oracle資料庫
- Spring Boot MyBatis配置多種資料庫Spring BootMyBatis資料庫
- Spring資料訪問Spring
- Power Builder同時連線多個資料庫(轉)UI資料庫
- mysql 同時插入幾行不同的資料 。MySql
- [資料庫] Navicat for MySQL換種思維解決插入同時更新資料資料庫MySql
- Java訪問資料庫的具體步驟:Java資料庫
- 使用speedment以Java 8 Stream訪問資料庫Java資料庫
- Java 8 徹底改變資料庫訪問Java資料庫
- JDBC資料庫訪問JDBC資料庫
- Spring4學習(三)JdbcTemplate訪問資料庫SpringJDBC資料庫
- 多個人訪問實體Bean,這個Bean訪問幾次資料庫啊?Bean資料庫
- 不同使用者訪問資料--current schema
- 臨時表在Oracle資料庫與SQL Server資料庫中的異同Oracle資料庫SQLServer
- Oracle資料庫中的多種SCN彙總Oracle資料庫
- Spring Boot入門(五):使用JDBC訪問MySql資料庫Spring BootJDBCMySql資料庫
- Spring Boot應用中如何動態指定資料庫,實現不同使用者不同資料庫的場景Spring Boot資料庫
- Oracle資料庫訪問控制Oracle資料庫
- 異構資料庫訪問資料庫
- 如何在資料訪問層中引用資料庫連線池?資料庫
- GUI應用程式該以何種方式訪問資料庫?GUI資料庫
- spring boot(四)資料訪問模組Spring Boot
- 同一Excel資料來源同時運用多種型別圖表Excel型別
- jboss訪問資料庫的問題資料庫
- 解決內、外網同時訪問問題
- J2EE中幾種物件導向的資料庫對映訪問策略:物件資料庫
- 同步整合不同系統、不同資料庫中資料的問題資料庫
- 通過shell指令碼同時監控多個資料庫負載指令碼資料庫負載
- 在不同的資料庫中解析SQLServer資料資料庫SQLServer
- [轉][資料庫SQL語句]truncate/delete/drop同與不同資料庫SQLdelete
- 不同資料庫間傳遞資料的問題資料庫
- 資料庫Delete的多種用法資料庫delete
- 讓Django支援多種資料庫Django資料庫