Springboot中數據庫訪問的兩種方式之-JdbcTemplate

目錄

 

01、寫在前面

02、項目依賴

03、創建模型腳本

04、讀取數據庫

05、Controller

06、開始測試


本文由bingo創作,授權我原創發佈。

Tiger和他朋友們的原創技術文章,請關注wx  “跟哥一起學python”,ID “tiger-python”。不止Python!!


在大多數的項目開發中,我們都有把數據存入數據庫和從數據庫中讀取的操作,所以與數據庫打交道是必不可少的。

衆所周知,spring提供了很多工具,我們拿來就可以用,使我們的項目開發更方便、快捷(作爲一個拿來主義者,很稀飯這種方式),今天我們就來看看springboot中如何從數據庫中讀取數據的。

一般來說,springboot中讀取數據庫的方式主要有兩種:JdbcTemplate和Jpa,今天我們先講講JdbcTemplate。

 

01、寫在前面


首先,我們理一下數據庫操作的一般流程。通常我們操作數據庫都需要創建連接和資源、從數據庫中讀取數據、異常處理和關閉資源的流程,代碼大概如下:


public Student findOne(String name) throws SQLException {
    Connection connection = null;
    PreparedStatementstatement = null;
    ResultSet resultSet= null;
    try {
        //1. 創建連接和各種資源
        connection =dataSource.getConnection();
        statement =connection.prepareStatement(
                "select id,name, grade from student");
        statement.setString(1, id);
        resultSet =statement.executeQuery();
        //2. 從resultSet中取出數據庫中數據來初始化Student
        Student Student = null;
        if(resultSet.next()){
            resultSet = new Student(
                    resultSet.getString("id"),
                    resultSet.getString("name"),
                    resultSet.getString("grade"),));
        }
        return Student;
    } catch (SQLException e){
        //3.處理異常
    }
    finally {
        //4.釋放資源
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e){}
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e){}
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e){}
        }
    }
    return null;
}

但是,看看上面那麼大篇幅的代碼,我們真正業務相關的就只有從數據庫中讀取那4行代碼,其它的代碼都是一些輔助和善後操作。

而JdbcTemplate就是對上面代碼的封裝,我們就只關心我們的業務代碼啦,其它的創建資源,釋放資源這些操作就由JdbcTemplate代我們效勞了。

本來還想說點啥,但是有位大神說過:talk is cheap, show me the code,所以......我還是shutup,直接擼代碼吧。

 

 

02、項目依賴

 

先上項目依賴:

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.11.0</version>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
</dependency>

作爲一個web項目,使用了spring-boot-starter-web和thymeleaf,使用了jackson-databind的ObjectMapper把類對象轉換城json串,本節講的是JdbcTemplate方式,所以spring-boot-starter-data-jdbc必不可少,數據庫測試我們使用了h2,嵌入式的內存數據庫。

 

 

03、創建模型腳本

 

今天的主角是一張學生表,我們的操作就是從學生表中讀取學生數據並呈現。

我們先創建學生表schema.sql並放入resources目錄下,這樣項目啓動的時候就會執行這個sql腳本。

 

CREATE TABLE IF NOT EXISTS STUDENT(id bigint identity primary key,

    name varchar(20) not null,

    grade varchar(20) not null

);

然後再創建data.sql,插入初始數據,同樣放入resources目錄下,這個腳本在項目啓動的時候也會執行。

 

delete fromstudent;
insert into student(name, grade) values ('bb', '01');
insert into student(name, grade) values ('cc', '02');

創建好後目錄結構像這樣:

 

同樣,代碼中也需要一個student的模型,內部數據和數據庫的一樣:

public class Student {    private Long ID;

    private String name;
    private String grade;

    public Student(Long ID, String name, String grade) {
        this.ID = ID;
        this.name = name;
        this.grade = grade;
    }

    public Long getID() {
        return ID;
    }

    public void setID(Long ID) {
        this.ID = ID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGrade() {
        return grade;
    }

}

作爲一個拿來主義者,最不爽的就是看別人文章時,只有部分代碼,看的我雲裏霧裏,暈頭轉向。所以我一點不能做那個自己討厭的人。

 

 

04、讀取數據庫

下面是從數據庫讀取的代碼,也是本篇文章的核心部分:​​​​​​​

@Repositorypublic class StudentRepository{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Student findStudentByName(String name) {
        return jdbcTemplate.queryForObject("select * from student where name = ?", new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                return new Student(resultSet.getLong("id"),
                        resultSet.getString("name"),
                        resultSet.getString("grade"));
            }
        }, name);
    }

}

@Reponsitory標識這是一個跟數據庫相關的Bean,會被自動掃描和實例化,JdbcTemplate添加上Autowired註解後拿來就可以用,這裏我們使用的是它的queryForObject方法來從數據庫中獲取數據。可以看到,queryForObject方法的參數除了接收一條sql語句外,還需要一個RowMapper的實現類,在實現類中去讀取數據。對比之前代碼中的那一大段,這兒就濃縮成了幾行,代碼簡潔了很多。

 

05、Controller

Web項目肯定要寫controller來進行測試咯,下面是controller代碼:​​​​​​​

@Controllerpublic class JdbcController {

    @Autowired
    private StudentRepository responsitory;

    @Autowired
    private ObjectMapper mapper;

    @GetMapping("/jdbc")
    public String queryStudent(@RequestParam("name") String name, Model model) {
        Student student = responsitory.findStudentByName(name);
        try {
            model.addAttribute("student", mapper.writeValueAsString(student));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "index";
    }

}

Controller中從url參數中獲取學生姓名,然後調用上面提供的接口來獲取student,再把student轉換成json串,放入model中,然後返回前端視圖index。

 

 

06、開始測試

 

好啦,我們來測試一下,運行程序,訪問http://localhost:8080/h2-console,看下數據是否真的插入進數據庫了。

 

正常!

作爲拿來主義者,必須要告訴你,h2console必須要配置spring.h2.console.enabled=true纔可訪問。

再訪問http://localhost:8080/jdbc?name=cc,看下從數據庫查詢數據是否正常?

 

完美!

但是你可能會好奇前端是怎麼顯示的,所以,拿走不謝:

​​​​​​​​​​​​​​

<!DOCTYPE html>

<html  xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="utf-8" />
      <title>示例</title>
      <link rel="stylesheet" th:href="@{/style.css}" />
   </head>

   <body>
      <div id="app" v-cloak>
         <template>
            <table>
               <thead>
                  <tr>
                     <th>ID</th>
                     <th>姓名</th>
                     <th>年級</th>
                  </tr>
               </thead>
               <tbody>
                  <tr>
                     <td>{{student.id}}</td>
                     <td>{{student.name}}</td>
                     <td>{{student.grade}}</td>
                  </tr>
               </tbody>
            </table>
         </template>
      </div>
      <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
      <script>
         var app = new Vue({
            el: '#app',
            data:{
               student: [(${student})]
            }
         })
</script>
   </body>
</html>

這裏用了一點Vue的東西,俺最近也在學。

下次我們講講Jpa是怎麼做的。


本文由bingo創作,授權我原創發佈。

Tiger和他朋友們的原創技術文章,請關注wx  “跟哥一起學python”,ID “tiger-python”。不止Python!!

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章