SpringBoot入門(mén)之CRUD

前言:

在大SpringMVC體系中雖然簡(jiǎn)化了配置,以及類的數(shù)量,一個(gè)控制器中多個(gè)方法可以分別對(duì)應(yīng)不同的業(yè)務(wù)。但是從根本上來(lái)說(shuō),需要的配置還是太多,搭建工程重復(fù)性的動(dòng)作還是太多,開(kāi)發(fā)速度還是不夠快。還應(yīng)當(dāng),或者說(shuō)還可以進(jìn)一步簡(jiǎn)化,這時(shí)SpringBoot橫空出世。

簡(jiǎn)介:

SpringBoot 開(kāi)啟了各種自動(dòng)裝配,就是為了簡(jiǎn)化開(kāi)發(fā),不需要寫(xiě)各種配置文件,只需要引入相關(guān)的依賴就能迅速搭建起一個(gè)web工程。

  1. 不需要任何的web.xml配置。
  2. 不需要任何的spring mvc的配置。
  3. 不需要配置tomcat ,springboot內(nèi)嵌tomcat.
  4. 不需要配置jackson,良好的restful風(fēng)格支持,自動(dòng)通過(guò)jackson返回json數(shù)據(jù)
  5. 個(gè)性化配置時(shí),最少一個(gè)配置文件可以配置所有的個(gè)性化信息

需求簡(jiǎn)介

  1. 實(shí)現(xiàn)關(guān)于Student的增刪該查
  2. 編碼采用restful風(fēng)格
  3. 數(shù)據(jù)庫(kù)使用Map結(jié)構(gòu)代替
  4. 開(kāi)發(fā)工具使用IntelliJ IDEA

構(gòu)建工程

1. 工具準(zhǔn)備

JDK1.8+
Maven 3.0+
IDEA 2016+

2. 創(chuàng)建過(guò)程

create.gif

3. 引入依賴

importDependency.gif

4. pom.xml完整內(nèi)容

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-spring-boot</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>

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

    <properties>
        <java.version>1.8</java.version>
    </properties>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

5. 工程目錄結(jié)構(gòu)

-src
  -main
    -java
      -cn
        -itcast
          -springboot
            -dao
            -service
            -entity
            -controller
            -Main.java
    -resouces
           
  -test
- pom

6. 實(shí)體Bean,Student.java編寫(xiě)

package cn.itcast.springboot.entity;

import java.io.Serializable;
import java.util.Date;

public class Student implements Serializable{
    private Long id;
    private String name;
    private int age;
    private Date birth;

    public Student() {
    }

    public Student(Long id, String name, int age, Date birth) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.birth = birth;
    }

    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 int getAge() {
        return age;
    }

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

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", birth=" + birth +
                '}';
    }
}

7. StudentDAO.java接口編寫(xiě)

package cn.itcast.springboot.dao;

import cn.itcast.springboot.entity.Student;

import java.util.Collection;

public interface StudentDAO {

    //獲取所有的student
    Collection<Student> getAllStudents();

    /**
     * @param id
     * 根據(jù)id獲取學(xué)生
     *
     * @return Student
     * 返回對(duì)應(yīng)的學(xué)生對(duì)象
     **/
    Student getStudentById(Long id);


    /**
     * @param student
     * 傳入新的student數(shù)據(jù)
     *
     * @return Collection<Student>
     * 修改成功后返回所有的student
     * */
    Collection<Student> updateStudentById(Student student);


    /**
     * @param student
     * 傳入新的student數(shù)據(jù)
     *
     * @return Collection<Student>
     * 新增成功后返回所有的student
     * */
    Collection<Student> addStudentById(Student student);


    /**
     * @param id
     * 傳入要?jiǎng)h除的student的id
     *
     * @return Collection<Student>
     * 刪除成功后返回所有的student
     * */
    Collection<Student> deleteStudentById(Long id);
}

8. StudentDAOImpl.java 實(shí)現(xiàn)類編寫(xiě)

package cn.itcast.springboot.dao;

import cn.itcast.springboot.entity.Student;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Repository("fakeDAO")
public class StudentDAOImpl implements StudentDAO {

    Map<Long,Student> studentMap = new HashMap<Long,Student>(){{
        put(10086L,new Student(10086L,"劉德華",50,new Date()));
        put(10087L,new Student(10087L,"張學(xué)友",51,new Date()));
        put(10088L,new Student(10088L,"霍建華",52,new Date()));
        put(10089L,new Student(10089L,"郭富城",53,new Date()));
        put(10090L,new Student(10090L,"陳冠希",54,new Date()));
    }};

    @Override
    public Collection<Student> getAllStudents() {
        return studentMap.values();
    }

    @Override
    public Student getStudentById(Long id) {
        return studentMap.get(id);
    }

    @Override
    public Collection<Student> updateStudentById(Student student) {
        studentMap.put(student.getId(),student);
        return studentMap.values();
    }

    @Override
    public Collection<Student> addStudentById(Student student) {
        studentMap.put(student.getId(),student);
        return studentMap.values();
    }

    @Override
    public Collection<Student> deleteStudentById(Long id) {
        studentMap.remove(id);
        return studentMap.values();
    }
}

9. StudentService.java 接口編寫(xiě)

package cn.itcast.springboot.service;

import cn.itcast.springboot.entity.Student;

import java.util.Collection;

public interface StudentService {

    //獲取所有的student
    Collection<Student> getAllStudents();

    /**
     * @param id
     * 根據(jù)id獲取學(xué)生
     *
     * @return Student
     * 返回對(duì)應(yīng)的學(xué)生對(duì)象
     **/
    Student getStudentById(Long id);


    /**
     * @param student
     * 傳入新的student數(shù)據(jù)
     *
     * @return Collection<Student>
     * 修改成功后返回所有的student
     * */
    Collection<Student> updateStudentById(Student student);


    /**
     * @param student
     * 傳入新的student數(shù)據(jù)
     *
     * @return Collection<Student>
     * 新增成功后返回所有的student
     * */
    Collection<Student> addStudentById(Student student);


    /**
     * @param id
     * 傳入要?jiǎng)h除的student的id
     *
     * @return Collection<Student>
     * 刪除成功后返回所有的student
     * */
    Collection<Student> deleteStudentById(Long id);
}

10. StudentServiceImpl.java 實(shí)現(xiàn)類編寫(xiě)

package cn.itcast.springboot.service;

import cn.itcast.springboot.dao.StudentDAO;
import cn.itcast.springboot.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDAO studentDAO;

    @Override
    public Collection<Student> getAllStudents() {
        return studentDAO.getAllStudents();
    }

    @Override
    public Student getStudentById(Long id) {
        return studentDAO.getStudentById(id);
    }

    @Override
    public Collection<Student> updateStudentById(Student student) {
        return studentDAO.updateStudentById(student);
    }

    @Override
    public Collection<Student> addStudentById(Student student) {
        return studentDAO.addStudentById(student);
    }

    @Override
    public Collection<Student> deleteStudentById(Long id) {
        return studentDAO.deleteStudentById(id);
    }
}

11. StudentController.java 控制器編寫(xiě)

package cn.itcast.springboot.controller;

import cn.itcast.springboot.entity.Student;
import cn.itcast.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
@RequestMapping("students")
public class StudentController {
   @Autowired
   private StudentService studentService;

   @GetMapping
   public Collection<Student> getAllStudents(){
       return studentService.getAllStudents();
   }
}

12. Main.java 主文件編寫(xiě)

package cn.itcast.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

13. 文件目錄

tree.png

14. 測(cè)試運(yùn)行

show.gif

15. StudentController.java 細(xì)節(jié)描述

@RequestMapping("students") //配置全局的訪問(wèn)方式
@GetMapping //在全局的訪問(wèn)基礎(chǔ)上擴(kuò)充訪問(wèn),后面不加參數(shù),表示用來(lái)匹配全局訪問(wèn) http://localhost:8080/students,訪問(wèn)方式為GET

16. 重點(diǎn)知識(shí)介紹之@RequestMapping

  • RequestMapping的原生用法之常見(jiàn)屬性
  • name:指定請(qǐng)求映射的名稱,一般省略
  • value:指定請(qǐng)求映射的路徑
  • method:指定請(qǐng)求的method類型, 如,GET、POST、PUT、DELETE等;
  • consumes:指定處理請(qǐng)求的提交內(nèi)容類型(Content-Type),例如application/json, text/html;
  • produces:指定返回的內(nèi)容類型,僅當(dāng)request請(qǐng)求頭中的(Accept)類型中包含該指定類型才返回;

17. 衍生映射:GetMapping,PostMapping,PutMapping,DeleteMapping

  • 這一系列mapping與RequestMapping相類似,可以看作簡(jiǎn)化版描述
  • 簡(jiǎn)單比較如:
  1. RequestMapping(method = RequestMethod.GET),含義與GetMapping相同
  2. PostMapping(method = RequestMethod.POST),含義與PostMapping相同
  3. PutMapping與DeleteMapping同上

18.各種Mapping應(yīng)用場(chǎng)景綜述

  1. 修改數(shù)據(jù),PutMapping
  2. 刪除數(shù)據(jù),DeleteMapping
  3. 查詢數(shù)據(jù),GetMapping
  4. 新增數(shù)據(jù),PostMapping
  5. 總結(jié):通過(guò)請(qǐng)求方式來(lái)區(qū)分業(yè)務(wù)類別,使得URI變得更簡(jiǎn)單

19. 各種Mapping的用法簡(jiǎn)介

Mapping類型 URL 解釋
GET www.itcast.cn/students 獲取所有的學(xué)生信息
GET www.itcast.cn/students/10086 獲取id為10086的學(xué)生信息
POST www.itcast.cn/students 添加學(xué)生信息
PUT www.itcast.cn/students/10086/10086 修改id為10086的學(xué)生信息
DELETE www.itcast.cn/students/10086 刪除id為10086的學(xué)生信息

20. 實(shí)際Controller,StudentController.java設(shè)計(jì)

package cn.itcast.controller;

import cn.itcast.entity.Student;
import cn.itcast.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;


@RestController
@RequestMapping(name = "name", value = "/students",method = RequestMethod.GET)
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping
    public Collection<Student> getAllStudents() {

        return studentService.getAllStudents();

    }

    @GetMapping(value = "/{id}")
    public Student getStudentById(@PathVariable("id") Long id) {
        return studentService.getStudentById(id);
    }


    @DeleteMapping(value = "/{id}")
    public Collection<Student> deleteStudentById(@PathVariable("id") Long id) {
        return studentService.deleteStudentById(id);
    }

    @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public Collection<Student> updateStudentById(@RequestBody Student student) {
        return studentService.updateStudentById(student);
    }

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public Collection<Student> addStudent(@RequestBody Student student) {
        return studentService.addStudent(student);
    }
}

21. 細(xì)節(jié)描述

  1. 參數(shù)占位聲明,{paramNam}:
    @GetMapping(value = "/{id}")
  2. 應(yīng)用聲明參數(shù),@PathVariable("ParamName")
    public Student getStudentById(@PathVariable("id") Long id)
  3. 完整示例
@GetMapping(value = "/{id}")
    public Student getStudentById(@PathVariable("id") Long id) {
        return studentService.getStudentById(id);
    }
  1. 請(qǐng)求參數(shù)類型JSON化處理
@PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public Collection<Student> updateStudentById(@RequestBody Student student) {
        return studentService.updateStudentById(student);
    }

4.1. 通過(guò)consumes屬性指定請(qǐng)求參數(shù)的提交類型為JSON

@PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)

4.2. 通過(guò)@RequestBody 把請(qǐng)求提交的JSON數(shù)據(jù)轉(zhuǎn)換為對(duì)應(yīng)的JavaBean

public Collection<Student> updateStudentById(@RequestBody Student student)

22. 新增學(xué)生演示

addStudent.gif

23. 修改學(xué)生演示

updateStudent.gif

24. 刪除學(xué)生演示

deleteStudent.gif

25. 根據(jù)id查詢學(xué)生演示

queryById.gif

26. 關(guān)于日期類型配置

  1. 用戶輸入日期值存儲(chǔ)到數(shù)據(jù)庫(kù)Map中不需要任何配置
  2. 從Map中取出數(shù)據(jù)時(shí),由于通過(guò)jackson封裝,所以如果不做特殊配置,會(huì)把日期轉(zhuǎn)成從1970-01-01 00:00:00開(kāi)始到當(dāng)前時(shí)間的毫秒數(shù)。
  3. 配置日期的顯示格式
    3.1 在resources目錄中創(chuàng)建application.properties文件
    3.2 在文件中加入內(nèi)容
    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
    spring.jackson.time-zone=GMT+8
    3.3 總覽
overview.png

3.4 查詢測(cè)試

config.gif

27. 未完待續(xù)......下一篇,加入數(shù)據(jù)庫(kù)支持

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,699評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,290評(píng)論 6 342
  • 第二部分 Spring Framework 4.x中有什么新功能? 3. Spring Framework 4.0...
    步積閱讀 1,319評(píng)論 1 6
  • 又是加班加點(diǎn)的一天,回家路上,一路想著怎么哄妻子才能快速破解抱怨。門(mén)打開(kāi)的那一刻,是妻子擔(dān)心的責(zé)怪,老不吃飯...
    方方秋秋閱讀 339評(píng)論 0 0
  • 如今對(duì)于大多數(shù)團(tuán)隊(duì)而言,由于種種原因,共同參與正確方案的決策與執(zhí)行是一個(gè)難題。確定一個(gè)戰(zhàn)略決策是沒(méi)有固定套路的。未...
    赤橙醬閱讀 6,847評(píng)論 0 7

友情鏈接更多精彩內(nèi)容