SpringBoot入門之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ā)挽荠,不需要寫各種配置文件,只需要引入相關(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編寫

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接口編寫

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)類編寫

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 接口編寫

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)類編寫

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 控制器編寫

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 主文件編寫

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)系作者
  • 序言:七十年代末野哭,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子幻件,更是在濱河造成了極大的恐慌拨黔,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绰沥,死亡現(xiàn)場(chǎng)離奇詭異篱蝇,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)徽曲,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門零截,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人秃臣,你說(shuō)我怎么就攤上這事涧衙。” “怎么了奥此?”我有些...
    開(kāi)封第一講書人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵弧哎,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我稚虎,道長(zhǎng)撤嫩,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任蠢终,我火速辦了婚禮非洲,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蜕径。我一直安慰自己两踏,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布兜喻。 她就那樣靜靜地躺著梦染,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上帕识,一...
    開(kāi)封第一講書人閱讀 51,541評(píng)論 1 305
  • 那天泛粹,我揣著相機(jī)與錄音,去河邊找鬼肮疗。 笑死晶姊,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的伪货。 我是一名探鬼主播们衙,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼碱呼!你這毒婦竟也來(lái)了蒙挑?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤愚臀,失蹤者是張志新(化名)和其女友劉穎忆蚀,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體姑裂,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡馋袜,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了舶斧。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片桃焕。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖捧毛,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情让网,我是刑警寧澤呀忧,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站溃睹,受9級(jí)特大地震影響而账,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜因篇,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一泞辐、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧竞滓,春花似錦咐吼、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春肌幽,著一層夾襖步出監(jiān)牢的瞬間晚碾,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工喂急, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留格嘁,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓廊移,卻偏偏與公主長(zhǎng)得像糕簿,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子画机,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

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