使用 SpringBoot 寫增刪改查

使用 SpringBoot 寫增刪改查

一、前言

1晶丘、之前使用 SSM(Spring+SpringMVC+MyBatis)+Maven 寫后端的接口唐含,創(chuàng)建了不少 Maven 工程捷枯。一開始還覺得 SSM+Maven 是十分簡便的专执,但是后來審美疲勞本股,漸漸感覺這種固定化地創(chuàng)建 New Maven Project 是一件體力操作。

2苟径、比如那些 web.xml(全局配置)躬审、dispatch-Servlet.xml(SpringMVC配置)承边、applicationContext.xml(Spring配置)博助、mybatis-config.xml(MyBatis配置)等大同小異,一開始還會老老實實從0開始寫蛔糯,后來煩了直接復制粘貼之前的代碼城瞎。

3脖镀、SpringBoot 就解決這個硬傷狼电,很快建立工程肩碟,使用 SpringData 封裝數據庫訪問層基本 CURD 接口(SSM還得使用逆向工程)削祈,一個簡單的 application.yml 配置就搞定前面的所有配置脑漫,一手輕巧的注解取代了之前大量的代碼优幸。

這次根據 SpringBoot 官方API文檔等,測試一下基于 SpringBoot 的 CURD羹饰,同時啟用 Restful 風格碳却,編寫起代碼來,十分具有美感~

RESTful API:

RESTful API 目前是前后端分離最佳實踐

① 輕量馍资,直接通過 http座柱,不需要額外的協(xié)議

② 面向資源色洞,一目了然,具有自解釋性

③ 數據描述簡單锦针,一般通過 json 或 xml 做數據通信

二奈搜、依舊是簡單的 CRUD盯荤,后臺的基本

1秋秤、代碼結構

總體來說,還是采用了標準的編程模式绍哎,建立 entity崇堰、dao、service繁莹、controller 包進行分類包裝蒋困,部分接口采用 interface+implements。命名方面也有注意溉跃。

代碼應該是很規(guī)范的告抄。

2打洼、Student.java

實體

package com.cun.entity;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.Table;

import org.hibernate.validator.constraints.NotEmpty;

@Entity // 實體

@Table(name = "t_student") // 數據庫表名

public class Student {

@Id // 主鍵

@GeneratedValue // 自增

private Integer id;

@NotEmpty(message = "學生姓名不能為空") // 表單驗證

@Column(length = 20) // 字段長度

private String t_name;

@Column(length = 20) // 字段長度

private String major;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getT_name() {

return t_name;

}

public void setT_name(String t_name) {

this.t_name = t_name;

}

public String getMajor() {

return major;

}

public void setMajor(String major) {

this.major = major;

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

3募疮、StudentDao.java

dao 接口

實現類都不用寫了阿浓,SpringData-JPA 自動幫你實現芭毙,里邊雖然空空,但是單表基本CRUD接口都寫好了

package com.cun.dao;

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

import com.cun.entity.Student;

/**

* 簡單的dao層只需要繼承JpaRepository接口粘咖,即可瓮下,

* 兩個參數,分別表示 —— 實體類型两蟀、主鍵類型

* 復雜sql語句再自己增加接口

* @author linhongcun

*

*/

public interface StudentDao extends JpaRepository<Student, Integer>{

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

4赂毯、StudentService.java

事務處接口

package com.cun.service;

import java.util.List;

import com.cun.entity.Student;

public interface StudentService {

public void addStudent(Student student);

public void deleteStudent(Integer id);

public void updateStudent(Student student);

public Student findStudent(Integer id);

public List<Student> findAllStudent();

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

5党涕、StudentServiceImpl.java

事務處接口實現類

package com.cun.service.impl;

import java.util.List;

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

import org.springframework.stereotype.Service;

import com.cun.dao.StudentDao;

import com.cun.entity.Student;

import com.cun.service.StudentService;

@Service

public class StudentServiceImpl implements StudentService {

@Autowired?

private StudentDao studentDao;

@Override

public void addStudent(Student student) {

// TODO Auto-generated method stub

studentDao.save(student);

}

@Override

public void deleteStudent(Integer id) {

// TODO Auto-generated method stub

studentDao.delete(id);

}

@Override

public void updateStudent(Student student) {

// TODO Auto-generated method stub

studentDao.save(student);

}

@Override

public Student findStudent(Integer id) {

// TODO Auto-generated method stub

return studentDao.findOne(id);

}

@Override

public List<Student> findAllStudent() {

// TODO Auto-generated method stub

return studentDao.findAll();

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

6、StudentController.java

控制層

package com.cun.controller;

import java.util.List;

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

import org.springframework.web.bind.annotation.DeleteMapping;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.PutMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.cun.entity.Student;

import com.cun.service.StudentService;

//@RestController 代替 @Controller,省略以后的 @ResponseBody

@RestController

@RequestMapping("/student")

public class StudentController {

@Autowired

private StudentService studentservice;

/**

* 顯示所有

* url:"http://localhost/student/findall"

*

* @return

*/

@RequestMapping(value = "/findall")

public List<Student> findAllStudent() {

return studentservice.findAllStudent();

}

/**

* 查找 restful 風格

* url:"http://localhost/student/findone/1"

*

* @param id

* @return

*/

// == @RequestMapping(value = "/findone/{id}", method = RequestMethod.GET)

@GetMapping("/findone/{id}")

public Student findStudentRestful(@PathVariable("id") Integer id) {

return studentservice.findStudent(id);

}

/**

* 刪除 restful 風格

* url:"http://localhost/student/deleteone/4"

* 注意無法通過瀏覽器的鏈接來模擬檢驗,可以通過 jquery的 $.ajax方法,并type="delete"

*

* @param id

*/

// == @RequestMapping(value = "/deleteone/{id}", method = RequestMethod.DELETE)

@DeleteMapping("/deleteone/{id}")

public void deleteStudentRestful(@PathVariable("id") Integer id) {

studentservice.deleteStudent(id);

}

/**

* 增加 restful 風格

* url:"http://localhost/student/addone"

* 通過<form>表單模擬驗證

*

* @param student

*/

// == @RequestMapping(value="/addone",method=RequestMethod.POST)

@PostMapping("/addone")

public void addStudentRestful(Student student) {

studentservice.addStudent(student);

}

/**

* 修改 restful 風格

* url:"http://localhost/student/updateone"

* 驗證:可以通過 jquery的 $.ajax方法燕耿,并type="put",同時注意data形式——A=a&B=b&C=c

*

* @param student

*/

// == @RequestMapping(value="/addone",method=RequestMethod.PUT)

@PutMapping("/updateone")

public void updateStudentRestful(Student student) {

studentservice.updateStudent(student);

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

7、index.html

接口測試蚜锨,這里寫得有點簡陋慢蜓,不過還是可以正確測試接口寫得是否有問題

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title></title>

<script src="js/jquery-1.7.2.js"></script>

<script type="text/javascript">

/**

* 實際應用時胀瞪,里邊的參數應根據實際而改變,而不是寫死的圆雁,

* 這里僅僅①簡單地模擬前后端伪朽,②簡單測試接口

*

*/

function del() {

$.ajax({

type : "delete",

url : "http://localhost/student/deleteone/4",

async : true

});

}

function upd() {

$.ajax({

type : "put",

data:"id=6&t_name=cun&major=計科",

url : "http://localhost/student/updateone",

async : true

});

}

</script>

</head>

<body>

<!-- 刪除 -->

<button id="btn" onclick="del()">delete request</button>

<!-- 更新 -->

<button id="btn2" onclick="upd()">update request</button>

<!-- 增加 -->

<form action="http://localhost/student/addone" method="post">

major<input type="text" name="major" />

t_name<input type="text" name="t_name" />

<input type="submit" value="submit" />

</form>

<!-- 查詢 -->

<a href="http://localhost/student/findone/6">select request</a>

</body>

</html>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

8烈涮、application.yml

配置坚洽,算是很簡單了讶舰,下面幾個配置是最常用的

server:

? port: 80 #為了以后訪問項目不用寫端口號

? context-path: / #為了以后訪問項目不用寫項目名

spring:

? datasource:

? ? driver-class-name: com.mysql.jdbc.Driver

? ? url: jdbc:mysql://localhost:3306/testspring

? ? username: root

? ? password: 123

? jpa:

? ? hibernate:

? ? ? ddl-auto: update? #數據庫同步代碼

? ? show-sql: true? ? ? #dao操作時,顯示sql語句

1

2

3

4

5

6

7

8

9

10

11

12

13

9般甲、pom.xml

在 eclipse 創(chuàng)建 SpringBoot 工程時加入

以后再加入 mysql、jpa鹅颊、web 就好了敷存,并且可以通過 Alt+/ => Edit Starter 加入

三、小結

SpringBoot官方中文參考文檔

【思考:SpringBoot 自動配置】

首先堪伍,這是基于 Spring4+ 版本的

①采用注解 bean 的方式進行配置

②習慣優(yōu)于配置锚烦,自動加載了大量的常用的配置方式,如 SpringMVC+Spring杠娱,視圖解析器挽牢、控制器等

③又可更改,如修改 SpringMVC摊求,@Configuration+@Bean刘离,修改上述自動配置室叉。

————————————————

版權聲明:本文為CSDN博主「larger5」的原創(chuàng)文章,遵循 CC 4.0 BY 版權協(xié)議硫惕,轉載請附上原文出處鏈接及本聲明茧痕。

原文鏈接:https://blog.csdn.net/larger5/article/details/79325999

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市恼除,隨后出現的幾起案子踪旷,更是在濱河造成了極大的恐慌,老刑警劉巖豁辉,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件令野,死亡現場離奇詭異,居然都是意外死亡徽级,警方通過查閱死者的電腦和手機气破,發(fā)現死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來餐抢,“玉大人现使,你說我怎么就攤上這事低匙。” “怎么了碳锈?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵顽冶,是天一觀的道長。 經常有香客問我售碳,道長强重,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任团滥,我火速辦了婚禮竿屹,結果婚禮上,老公的妹妹穿的比我還像新娘灸姊。我一直安慰自己拱燃,他們只是感情好,可當我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布力惯。 她就那樣靜靜地躺著碗誉,像睡著了一般。 火紅的嫁衣襯著肌膚如雪父晶。 梳的紋絲不亂的頭發(fā)上哮缺,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天,我揣著相機與錄音甲喝,去河邊找鬼尝苇。 笑死,一個胖子當著我的面吹牛埠胖,可吹牛的內容都是我干的糠溜。 我是一名探鬼主播,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼直撤,長吁一口氣:“原來是場噩夢啊……” “哼非竿!你這毒婦竟也來了?” 一聲冷哼從身側響起谋竖,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤红柱,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后蓖乘,有當地人在樹林里發(fā)現了一具尸體锤悄,經...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年驱敲,在試婚紗的時候發(fā)現自己被綠了铁蹈。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖握牧,靈堂內的尸體忽然破棺而出容诬,到底是詐尸還是另有隱情,我是刑警寧澤沿腰,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布览徒,位于F島的核電站,受9級特大地震影響颂龙,放射性物質發(fā)生泄漏习蓬。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一措嵌、第九天 我趴在偏房一處隱蔽的房頂上張望躲叼。 院中可真熱鬧,春花似錦企巢、人聲如沸枫慷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽或听。三九已至,卻和暖如春笋婿,著一層夾襖步出監(jiān)牢的瞬間誉裆,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工缸濒, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留足丢,地道東北人。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓庇配,卻偏偏與公主長得像霎桅,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子讨永,可洞房花燭夜當晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內容