SpringBoot系列(4)——數據庫操做

前言:

數據庫操做使用了Spring-Data-Jpa和MySQL,什麼是Spring-Data-Jpa呢?java

Spring-Data-Jpa是Spring對Hibernate的整合,關於Spring-Data-Jpa的詳細內容,後面會寫一系列相關的筆記。mysql

數據庫操做的RESTful API設計以下:web

請求類型 請求路徑 功能
GET /student 獲取學生列表
POST /student 建立一個學生
GET /student/id 經過id查詢一個學生
PUT /student/id 經過id更新一個學生
DELETE /student/id 經過id刪除一個學生

 

一. 具體操做:


1. 添加兩個依賴:

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

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

2. 在application.yml中進行相關數據庫的配置:

spring:
  profiles:
    active: prod
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/testSprigBoot?useSSL=false
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true

ddl-auto幾個參數值表明的意義:spring

  • create    每次程序運行都會建立新表,若是以前數據庫裏有該表,則會被刪除,再建新表
  • update    第一次運行也會建立對應的表結構,可是以後運行若是表中有數據,不會被刪除
  • create-drop 應用停下來的時候,會把表刪掉
  • none        默認不採起任何操做
  • validate    驗證類中的屬性和表結構是否一致,若不一致則報錯

show-sql : 是否能夠在控制檯看到sql語句sql

3. 手動新建數據庫「testSpringBoot」

(utf8mb4兼容utf8,因此能支持更多的字符集,關於emoji表情的話mysql的utf8是不支持,須要修改設置爲utf8mb4,才能支持)數據庫

4. 設置實體類(建立數據庫對象,即表的映射)

package com.example.demo;

import org.springframework.data.annotation.Id;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;

/**
 * Created by xzf on 2017/9/17.
 */
@Entity
public class Student {
    @javax.persistence.Id
    @GeneratedValue
    private Integer id;

    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

運行程序後,沒必要寫sql語句,便可自動在數據庫中建立student表json

以上實體類代碼有一些須要注意的點:app

  1. 要在類前使用 @Entity 註解標註該類爲實體類
  2. @Id 註解很是容易選錯,應該選擇 @javax.persistence.Id,選其餘的類型會報錯
  3. 使用 @GenerateValue 使id自增

二. 根據設計的 RESTful API 進行增刪改查操做:

1. 新建一個StudentRepository的接口,讓其繼承自JpaRepository的接口:

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;

import java.util.List;

public interface StuentRepository extends JpaRepository<Student,Integer> {
    //經過年齡來查詢
    public List<Student> findByAge(Integer age);
}

2. 新建 StudentController 類,在該類中實現增刪改查操做:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by xzf on 2017/9/17.
 */
@RestController
public class StudentController {
    @Autowired
    private StuentRepository stuentRepository ;

    /**
     * 查詢全部學生列表
     * @return
     */
    @GetMapping("/students")
    public List<Student> studentList(){
        return stuentRepository.findAll();
    }

    /**
     * 添加一個學生
     */
    @PostMapping("/students")
    public Student studentAdd(@RequestParam("name") String name,
                             @RequestParam("age") Integer age){
        Student student=new Student();
        student.setName(name);
        student.setAge(age);
        return stuentRepository.save(student);
    }

    /**
     * 經過id查詢一個學生
     */
    @GetMapping("/students/{id}")
    public Student studentFindOne(@PathVariable("id") Integer id){
        return stuentRepository.findOne(id);
    }
    /**
     *經過id更新一個學生
     */
    @PutMapping("/students/{id}")
    public Student studentUpdate(@PathVariable("id") Integer id,
                              @RequestParam("name") String name,
                              @RequestParam("age") Integer age){
        Student student=new Student();
        student.setId(id);
        student.setName(name);
        student.setAge(age);
        return stuentRepository.save(student);
    }
    /**
     *經過id刪除一個學生
     */
    @DeleteMapping("/students/{id}")
    public void studentDel(@PathVariable("id") Integer id){
        stuentRepository.delete(id);
    }

    //經過年齡查詢學生列表
    @GetMapping("/students/age/{age}")
    public List<Student> studentListByAge(@PathVariable("age") Integer age){
        return stuentRepository.findByAge(age);
    }
}

以上代碼的測試能夠在Postman中進行,Postman能夠方便的模擬各類類型的請求操做(GET,POST,PUT,DELETE等),而且能給出直觀地返回json結果數據,很是方便。spring-boot

在測試PUT請求時,要注意,Postman中Body應該選擇圖中選項,而不是默認的form-data!測試

三. 事務管理

這裏主要涉及到一個註解的使用——@Transactional

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
public class StudentService {

    @Autowired
    private StuentRepository stuentRepository;

    @Transactional
    public void insertTwo(){

        Student studentA=new Student();
        studentA.setName("J");
        studentA.setAge(10);
        stuentRepository.save(studentA);

        Student studentB=new Student();
        studentB.setName("laka");
        studentB.setAge(20);
        stuentRepository.save(studentB);

    }
}

如上代碼,在insertTwo()方法前加上@Transactional註解,在該方法執行過程當中,若是發生錯誤,則會自動回滾。具體表現爲:insertTwo方法執行的操做爲新增兩個學生A和B,若執行過程當中有一個學生新增操做出現錯誤,則會回滾,數據庫中不會留下任何一個學生的插入結果。

相關文章
相關標籤/搜索