Spring Boot入門系列(十四)使用JdbcTemplate操作數(shù)據(jù)庫,配置多...

Spring Boot 除了Mybatis數(shù)據(jù)庫ORM框架,還有JdbcTemplate等數(shù)據(jù)庫操作框架,同樣也比較簡單實用,如果是一般簡單的項目,用JdbcTemplate完全可以實現(xiàn)相關(guān)的數(shù)據(jù)庫操作。它雖然沒有MyBatis功能強大,但使用比較簡單,JdbcTemplate應(yīng)該算是最簡單的數(shù)據(jù)持久化方案,所以下面就來給大家介紹Spring Boot 使用JdbcTemplate操作數(shù)據(jù)庫,配置多數(shù)據(jù)源!
?
一、JDBC簡介
JDBC(Java Data Base Connectivity, Java 數(shù)據(jù)庫連接)是一種用于執(zhí)行各種數(shù)據(jù)庫操作的 API,可以為多種數(shù)據(jù)庫提供統(tǒng)一訪問接口。所以,JDBC 就像是一套 Java 訪問數(shù)據(jù)庫的 API 規(guī)范,利用這套規(guī)范屏蔽了各種數(shù)據(jù)庫 API 調(diào)用的差異性。當(dāng)應(yīng)用程序需要訪問數(shù)據(jù)庫時,調(diào)用 JDBC API 相關(guān)代碼進新操作,再由JDBC調(diào)用各類數(shù)據(jù)庫的驅(qū)動包進行數(shù)據(jù)操作,最后數(shù)據(jù)庫驅(qū)動包和對應(yīng)的數(shù)據(jù)庫通訊協(xié)議完成對應(yīng)的數(shù)據(jù)庫操作。
在Java領(lǐng)域,數(shù)據(jù)持久化有幾個常見的方案,有Spring Boot自帶的JdbcTemplate、有MyBatis,還有JPA,在這些方案中,最簡單的就是Spring Boot自帶的JdbcTemplate,雖然沒有MyBatis功能強大,但是,使用比較簡單,事實上,JdbcTemplate應(yīng)該算是最簡單的數(shù)據(jù)持久化方案。
?
二、快速開始
開始之前,需要創(chuàng)建一個Spring Boot項目,JdbcTemplate的引用很簡單,開發(fā)者在創(chuàng)建一個SpringBoot項目時,選上Jdbc以及數(shù)據(jù)庫驅(qū)動依賴即可。之前介紹過如何創(chuàng)建項目這里就不介紹,直接使用之前創(chuàng)建的項目工程。
1、依賴配置
1、pom添加依賴
<dependency><groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-jdbcartifactId>dependency><dependency><groupId>mysqlgroupId><artifactId>mysql-connector-javaartifactId>dependency>
需要注意的是:
如果是用數(shù)據(jù)庫連接池,記得添加Druid數(shù)據(jù)庫連接池依賴。
這里可以添加專門為Spring Boot打造的druid-spring-boot-starter,JdbcTemplate默認使用Hikari 連接池,如果需要使用druid,需要另外配置。
?
2、application.properties配置數(shù)據(jù)源
接下來需要在application.properties中提供數(shù)據(jù)的基本配置即可,如下:
spring.datasource.url=jdbc:mysql://localhost:3306/zwz_testspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver
注意:在?Spring Boot 2.1.0?中,?com.mysql.jdbc.Driver?已經(jīng)過期,推薦使用com.mysql.cj.jdbc.Driver
如此之后,所有的配置就算完成了,接下來就可以直接使用JdbcTemplate了,是不是特別方便。其實這就是SpringBoot的自動化配置帶來的好處。
?
2、數(shù)據(jù)庫和實體類
1、數(shù)據(jù)庫表
DROP TABLE IF EXISTS `products`;CREATE TABLE `products` (`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',`name` varchar(32) DEFAULT NULL COMMENT '名稱',`code` varchar(32) DEFAULT NULL COMMENT '編碼',`price` int DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
?
2、實體類
package com.weiz.pojo;public class Product {private Long id;private String name;private String code;private int price;public Product(String name, String code, int price) {this.name = name;this.code = code;this.price = price;}// 省略 getter setter}
實體類的數(shù)據(jù)類型要和數(shù)據(jù)庫字段一一對應(yīng),否則會有問題。
3、Serverice封裝
創(chuàng)建ProductService和ProductServiceImpl類
1、創(chuàng)建?UserService 定義我們常用的增刪改查接口
package com.weiz.service;import com.weiz.pojo.Product;public interface ProductService {int save(Product product);int update(Product product);int delete(long id);Product findById(long id);}復(fù)制代碼2、創(chuàng)建 ProductServiceImpl 類實現(xiàn) ProductService 類接口復(fù)制代碼package com.weiz.service.impl;import com.weiz.pojo.Product;import com.weiz.service.ProductService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Service;public class ProductServiceImpl implements ProductService {private JdbcTemplate jdbcTemplate;public int save(Product product) {return jdbcTemplate.update("INSERT INTO products(name, code, price) values(?, ? , ?)",product.getName(), product.getCode(), product.getPrice());}public int update(Product product) {return jdbcTemplate.update("UPDATE products SET name = ? , code = ? , price = ? WHERE id=?",product.getName(), product.getCode(), product.getPrice(), product.getId());}public int delete(long id) {return jdbcTemplate.update("DELETE FROM products where id = ? ",id);}public Product findById(long id) {return jdbcTemplate.queryForObject("SELECT * FROM products WHERE id=?", new Object[] { id }, new BeanPropertyRowMapper(Product.class)); }}
上面的代碼,UserServiceImpl類上使用?@Service?注解用于標(biāo)注數(shù)據(jù)訪問組件,@Autowired 在類中注入?JdbcTemplate,JdbcTemplate是?Spring Boot操作JDBC?提供的工具類 。
除了以上這些基本用法之外,JdbcTemplate也支持其他用法,例如調(diào)用存儲過程等,這些都比較容易,而且和Jdbc本身都比較相似,這里也就不做介紹了,有興趣可以留言討論。
?
三、調(diào)用測試
?接下來我們對jdbc操作數(shù)據(jù)庫的功能進行測試。
1、創(chuàng)建ProductController?
package com.weiz.controller;import com.weiz.pojo.Product;import com.weiz.service.ProductService;import com.weiz.utils.JSONResult;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;public class ProductController {private ProductService productService;public JSONResult save() {Product product = new Product();product.setCode("iphone 11");product.setName("iphone 11");product.setPrice(100);productService.save(product);return JSONResult.ok("保存成功");}public JSONResult update() {long pid = 1;Product product = new Product();product.setCode("iphone 12");product.setName("iphone 12");product.setPrice(200);product.setId(pid);productService.update(product);return JSONResult.ok("修改成功");}public JSONResult delete(long pid) {productService.delete(pid);return JSONResult.ok("刪除成功");}public JSONResult findById(long pid) {Product product = productService.findById(pid);return JSONResult.ok(product);}}
2、啟動項目,在瀏覽器分別輸入增刪改查對應(yīng)的地址,測試對應(yīng)的方法是不是正確即可。

?
四、多數(shù)據(jù)源配置
在實際項目中,經(jīng)常會碰到使用多個數(shù)據(jù)源的情況, 比如:需要使用多個host、需要使用多種數(shù)據(jù)庫(MySql、Oracle、SqlServer...)。SpringBoot中,對此都有相應(yīng)的解決方案,不過一般來說,如果有多數(shù)據(jù)源的需求,我還是建議首選分布式數(shù)據(jù)庫中間件MyCat。這些都是比較成熟的框架,不需要自己重新寫一套。當(dāng)然如果一些簡單的需求,還是可以使用多數(shù)據(jù)源的,Spring Boot中,JdbcTemplate、MyBatis以及Jpa都可以配置多數(shù)據(jù)源。接下來,就在上面的項目的基礎(chǔ)上進行改造,給大家介紹JdbcTemplate 如何配置多數(shù)據(jù)源。
1、配置多數(shù)據(jù)源
application.properties配置多個數(shù)據(jù)源:
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/zwz_testspring.datasource.primary.username=rootspring.datasource.primary.password=rootspring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/zwz_test2spring.datasource.secondary.username=rootspring.datasource.secondary.password=rootspring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
上面的配置文件,添加了兩個數(shù)據(jù)源,一個是 zwz_test?庫,鈴個是 zwz_test2?庫。
注意:之前單個數(shù)據(jù)源的數(shù)據(jù)庫連接是:spring.datasource.url,這里多個數(shù)據(jù)源使用的是?spring.datasource.*.jdbc-url,因為JdbcTemplate默認使用Hikari 連接池,而?HikariCP?讀取的是?jdbc-url 。
?
2、配置JDBC初始化
創(chuàng)建DataSourceConfig,在項目啟動的時候讀取配置文件中的數(shù)據(jù)庫信息,并對?JDBC?初始化。??
package com.weiz.config;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.jdbc.DataSourceBuilder;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.jdbc.core.JdbcTemplate;import javax.sql.DataSource;@Configurationpublic class DataSourceConfig {@Primary@Bean(name = "primaryDataSource")@Qualifier("primaryDataSource")@ConfigurationProperties(prefix="spring.datasource.primary")public DataSource primaryDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "secondaryDataSource")@Qualifier("secondaryDataSource")@ConfigurationProperties(prefix="spring.datasource.secondary")public DataSource secondaryDataSource() {return DataSourceBuilder.create().build();}@Bean(name="primaryJdbcTemplate")public JdbcTemplate primaryJdbcTemplate (@Qualifier("primaryDataSource") DataSource dataSource ) {return new JdbcTemplate(dataSource);}@Bean(name="secondaryJdbcTemplate")public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {return new JdbcTemplate(dataSource);}}
上面的代碼,DataSourceConfig類的作用是在項目啟動的時候根據(jù)特定的前綴加載不同的數(shù)據(jù)源,再根據(jù)構(gòu)建好的數(shù)據(jù)源創(chuàng)建不同的 JDBC。?
?
注意事項:使用多個數(shù)據(jù)源時,需要添加@Primary注解,@Primary:自動裝配時當(dāng)出現(xiàn)多個Bean候選者時,被注解為@Primary的Bean將作為首選者。Primary 意味著"主要的",類似與SQL語句中的"primary key",有且只能有一個,否則會報錯。
?
?
3、修改Serverice封裝
需要對 ProductServerice 中的所有方法法進行改造,增加一個傳入?yún)?shù) JdbcTemplate,根據(jù)調(diào)用方傳入的JdbcTemplate 進行操作。
// ProductService 接口public interface ProductService {int save(Product product, JdbcTemplate jdbcTemplate);// 省略其他方法}// ProductServiceImplpublic class ProductServiceImpl implements ProductService {public int save(Product product,JdbcTemplate jdbcTemplate) {return jdbcTemplate.update("INSERT INTO products(name, code, price) values(?, ? , ?)",product.getName(), product.getCode(), product.getPrice());}// 省略其他方法}
?
4、調(diào)用測試
同樣,將之前的ProductController 修改如下:
public class ProductController {private ProductService productService;private JdbcTemplate primaryJdbcTemplate;private JdbcTemplate secondaryJdbcTemplate;public JSONResult save() {Product product = new Product();product.setCode("iphone 11");product.setName("iphone 11");product.setPrice(100);productService.save(product,primaryJdbcTemplate);productService.save(product,secondaryJdbcTemplate);return JSONResult.ok("保存成功");}// 省略其他方法}
啟動項目,在瀏覽器中輸入:http://localhost:8088/product/save??保存一條產(chǎn)品數(shù)據(jù)。
查看zwz_test 和 zwz_test2數(shù)據(jù)庫中的products表,都存入一條數(shù)據(jù),說明多數(shù)據(jù)源插入數(shù)據(jù)成功,其他方方法也是一樣的。這樣在實際項目中,我們通過傳入不同的JdbcTemplate 實例,就可以操作多個數(shù)據(jù)庫。
?
最后
以上,就把Spring Boot 使用jdbcTemplate 操作數(shù)據(jù)庫介紹完了。同時也介紹了如何配置使用多數(shù)據(jù)源。在?Spring Boot?項目中?JDBC?操作數(shù)據(jù)庫是不是非常簡單。
這個系列課程的完整源碼,也會提供給大家。大家關(guān)注我的微信公眾號(架構(gòu)師精進),回復(fù):springboot源碼。獲取這個系列課程的完整源碼。
?
推薦閱讀:
Spring Boot入門系列(十一)如何整合Mybatis,實現(xiàn)增刪改查【XML 配置版】
SpringBoot入門系列(五)Thymeleaf的常用標(biāo)簽和用法
SpringBoot入門系列(四)整合Thymeleaf模板引擎
Spring Boot整合Redis代碼詳解,四步搞定!
SpringBoot入門系列(二)Controller介紹及如何返回json數(shù)
Nginx總結(jié)(五)如何配置Nginx和Tomcat實現(xiàn)反向代理
Nginx總結(jié)(四)基于域名的虛擬主機配置
Nginx總結(jié)(一)如何安裝Nginx【詳細教程】

