1. 程式人生 > 其它 >SpringBoot學習筆記——SpringData與整合JDBC

SpringBoot學習筆記——SpringData與整合JDBC

  1. SpringBoot學習筆記——SpringBoot簡介與HelloWord
  2. SpringBoot學習筆記——原始碼初步解析
  3. SpringBoot學習筆記——配置檔案yaml學習
  4. SpringBoot學習筆記——JSR303資料校驗與多環境切換
  5. SpringBoot學習筆記——自動配置原理
  6. SpringBoot學習筆記——Web開發探究
  7. SpringBoot學習筆記——Thymeleaf
  8. SpringBoot學習筆記——簡單例項-員工管理系統

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-jdbc ; 引入相應的模組!基礎模組

2、專案建好之後,發現自動幫我們匯入瞭如下的啟動器:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</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已經預設幫我們進行了自動配置;去測試類測試一下

@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.sdz.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 employee";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    
    //新增一個使用者
    @GetMapping("/add")
    public String addUser(){
        //插入語句,注意時間問題
        String sql = "insert into employee(last_name, email,gender,department,birth)" +
                " values ('狂神說','[email protected]',1,101,'"+ new Date().toLocaleString() +"')";
        jdbcTemplate.update(sql);
        //查詢
        return "addOk";
    }

    //修改使用者資訊
    @GetMapping("/update/{id}")
    public String updateUser(@PathVariable("id") int id){
        //插入語句
        String sql = "update employee set last_name=?,email=? where id="+id;
        //資料
        Object[] objects = new Object[2];
        objects[0] = "秦疆";
        objects[1] = "[email protected]";
        jdbcTemplate.update(sql,objects);
        //查詢
        return "updateOk";
    }

    //刪除使用者
    @GetMapping("/delete/{id}")
    public String delUser(@PathVariable("id") int id){
        //插入語句
        String sql = "delete from employee where id=?";
        jdbcTemplate.update(sql,id);
        //查詢
        return "deleteOk";
    }
    
}

測試請求,結果正常;

到此,CURD的基本操作,使用 JDBC 就搞定了。