原文鏈接:公衆號狂神說
SpringData簡介
對於數據訪問層,無論是 SQL(關係型數據庫) 還是 NOSQL(非關係型數據庫),Spring Boot 底層都是採用 Spring Data 的方式進行統一處理。
Spring Boot 底層都是採用 Spring Data 的方式進行統一處理各種數據庫,Spring Data 也是 Spring 中與 Spring Boot、Spring Cloud 等齊名的知名項目。
Sping Data 官網:https://spring.io/projects/spring-data
數據庫相關的啓動器 :可以參考官方文檔:
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter
整合JDBC
創建測試項目測試數據源
1、我去新建一個項目測試:springboot-data; 引入相應的模塊!基礎模塊
2、項目建好之後,發現自動幫我們導入瞭如下的啓動器:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
3、編寫yaml配置文件連接數據庫;
spring:
datasource:
username: root
password: 123456
#?serverTimezone=UTC解決時區的報錯
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
4、配置完這一些東西后,我們就可以直接去使用了,因爲SpringBoot已經默認幫我們進行了自動配置;去測試類測試一下
package com.jia;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class SpringbootDataJdbcApplicationTests {
//DI注入數據源
@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
//看一下默認數據源
System.out.println(dataSource.getClass());
//獲得連接
Connection connection = dataSource.getConnection();
System.out.println(connection);
//關閉連接
connection.close();
}
}
結果:我們可以看到他默認給我們配置的數據源爲 : class com.zaxxer.hikari.HikariDataSource , 我們並沒有手動配置
我們來全局搜索一下,找到數據源的所有自動配置都在 :DataSourceAutoConfiguration文件:
@Import(
{Hikari.class, Tomcat.class, Dbcp2.class, Generic.class, DataSourceJmxConfiguration.class}
)
protected static class PooledDataSourceConfiguration {
protected PooledDataSourceConfiguration() {
}
}
這裏導入的類都在 DataSourceConfiguration 配置類下,可以看出 Spring Boot 2.2.5 默認使用HikariDataSource 數據源,而以前版本,如 Spring Boot 1.5 默認使用 org.apache.tomcat.jdbc.pool.DataSource 作爲數據源;
HikariDataSource 號稱 Java WEB 當前速度最快的數據源,相比於傳統的 C3P0 、DBCP、Tomcat jdbc 等連接池更加優秀;
可以使用 spring.datasource.type 指定自定義的數據源類型,值爲 要使用的連接池實現的完全限定名。
關於數據源我們並不做介紹,有了數據庫連接,顯然就可以 CRUD 操作數據庫了。但是我們需要先了解一個對象 JdbcTemplate
JDBCTemplate
1、有了數據源(com.zaxxer.hikari.HikariDataSource),然後可以拿到數據庫連接(java.sql.Connection),有了連接,就可以使用原生的 JDBC 語句來操作數據庫;
2、即使不使用第三方第數據庫操作框架,如 MyBatis等,Spring 本身也對原生的JDBC 做了輕量級的封裝,即JdbcTemplate。
3、數據庫操作的所有 CRUD 方法都在 JdbcTemplate 中。
4、Spring Boot 不僅提供了默認的數據源,同時默認已經配置好了 JdbcTemplate 放在了容器中,程序員只需自己注入即可使用
5、JdbcTemplate 的自動配置是依賴 org.springframework.boot.autoconfigure.jdbc 包下的 JdbcTemplateConfiguration 類
JdbcTemplate主要提供以下幾類方法:
-
execute方法:可以用於執行任何SQL語句,一般用於執行DDL語句;
-
update方法及batchUpdate方法:update方法用於執行新增、修改、刪除等語句;batchUpdate方法用於執行批處理相關語句;
-
query方法及queryForXXX方法:用於執行查詢相關語句;
-
call方法:用於執行存儲過程、函數相關語句。
測試
編寫一個Controller,注入 jdbcTemplate,編寫測試方法進行訪問測試;
package com.jia.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/jdbc")
public class JdbcController {
/**
* Spring Boot 默認提供了數據源,默認提供了 org.springframework.jdbc.core.JdbcTemplate
* JdbcTemplate 中會自己注入數據源,用於簡化 JDBC操作
* 還能避免一些常見的錯誤,使用起來也不用再自己來關閉數據庫連接
*/
@Autowired
JdbcTemplate jdbcTemplate;
//查詢employee表中所有數據
//List 中的1個 Map 對應數據庫的 1行數據
//Map 中的 key 對應數據庫的字段名,value 對應數據庫的字段值
@GetMapping("/list")
public List<Map<String, Object>> userList(){
String sql = "select * from student";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
//新增一個用戶
@GetMapping("/add")
public String addUser(){
//插入語句,注意時間問題
String sql = "insert into student(username,password,type)" +
" values ('小葉曲','123456789','ABC' )";
jdbcTemplate.update(sql);
//查詢
return "addOk";
}
//修改用戶信息
@GetMapping("/update/{id}")
public String updateUser(@PathVariable("id") int id){
//插入語句
String sql = "update student set username=?,password=? where id="+id;
//數據
Object[] objects = new Object[2];
objects[0] = "曲葉小";
objects[1] = "987654321";
jdbcTemplate.update(sql,objects);
//查詢
return "updateOk";
}
//刪除用戶
@GetMapping("/delete/{id}")
public String delUser(@PathVariable("id") int id){
//插入語句
String sql = "delete from student where id=?";
jdbcTemplate.update(sql,id);
//查詢
return "deleteOk";
}
}
測試請求,結果正常;
到此,CURD的基本操作,使用 JDBC 就搞定了。
B站地址:https://space.bilibili.com/95256449