參考鏈接
因為參考上面的博文發(fā)現(xiàn)有幾個問題撞蚕,解決問題之后把自己的完整步驟整理如下,在搭建項目時遇到的問題也整理出來过牙。我用的springboot的版本是2.1甥厦,參考博文應該是1.5,版本不一樣有些api就不一樣了寇钉,遇到問題可以看看參考刀疙。
springboot項目搭建(更新中)
環(huán)境:mac系統(tǒng)
所需工具:IDEA(jdk1.8)+mysql+postman
下載地址:idea、 mysql扫倡、mysql workbench谦秧、postman
-
創(chuàng)建項目
在idea界面通過file
—>new
—>projects
,選擇Spring Initializr
(是Spring 官方提供的一個用來初始化一個Spring boot 項目的工具)撵溃,選擇已有的jdk疚鲤,next
,輸入Group & Artifact(Group和Artifact等的含義),dependencies選擇所需的依賴包缘挑,基本的如圖所示集歇,注意圖片最右側一欄(如果建好項目了才發(fā)現(xiàn)少添加了包,在pom.xml配置文件中添加即可语淘;這些包具體的作用請自行百度)诲宇。
選擇依賴包
一路next直至finish,項目結構如圖所示:
項目結構
- 修改配置文件application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demoTest?characterEncoding=UTF-8&&useSSL=false&useUnicode=true
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
- demoTest對應你建立的數(shù)據(jù)庫,root和password分別對應你自己的用戶名惶翻、密碼
- spring.datasource.driver-class-name的值要注意姑蓝,要與springboot的版本相對應,1.5版本寫com.mysql.jdbc.Driver维贺,2.0以上版本寫com.mysql.cj.jdbc.Driver它掂。(參考:com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的區(qū)別)
- ddl-auto:update (介紹:ddl-auto的配置)表示該數(shù)據(jù)庫中如果沒有表,會自動創(chuàng)建溯泣,但是如果里面有數(shù)據(jù)虐秋,不會清空數(shù)據(jù)。
-
新建User類
在DemoApplication的父文件夾下分別新建entity、controller坑匠、dao包血崭,在entity包下新建user類(注意這里DemoApplication和各個包的位置是有講究的,具體原因可以自行百度厘灼,我也不是特別清楚原理夹纫,等我搞懂再來更新這個吧。還有為了代碼規(guī)范设凹,各個包具體用來放什么功能的代碼舰讹,還是需要更進一步學習(涉及到mvc模式等等))
package com.fn.example.entity;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "user")
@Data
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer age;
public User(){
}
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;
}
}
各個注解的作用可百度springboot data jpa注解,詳細學習(待更新)闪朱。
數(shù)據(jù)庫的表的名稱和代碼中@Table注解name的值對應月匣。
重新啟動項目,可以看到在本地數(shù)據(jù)庫中自動生成了數(shù)據(jù)庫的表user
-
新建UserRepository接口
在dao包下面新建UserRepository接口
(idea新建interface:new-Java Class-在kind下拉框選擇interface)
package com.jianshu.demo.dao;
import com.jianshu.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,Integer> {
}
-
新建UserController類
在controller包下新建UserController類
package com.jianshu.demo.controller;
import com.jianshu.demo.dao.UserRepository;
import com.jianshu.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
/*
select all data
*/
@GetMapping(value = "/all")
public List<User> getUserList(){
return userRepository.findAll();
}
/*
add a user
*/
@PostMapping(value = "/add")
public User addUser(@RequestParam("name") String name,@RequestParam("age") Integer age){
User user = new User();
user.setName(name);
user.setAge(age);
return userRepository.save(user);
}
/*
select a user based on id
*/
@GetMapping(value = "all/{id}")
public User getUser(@PathVariable("id") Integer id){
return userRepository.findById(id).orElse(null);
}
/*
delete a user based on id
*/
@DeleteMapping(value = "del/{id}")
public void deleteUser(@PathVariable("id") Integer id){
userRepository.deleteById(id);
}
}
-
測試
get方法可以直接用瀏覽器輸入监透,這里我們都用postman來模擬網(wǎng)頁請求桶错。
- 獲取數(shù)據(jù)庫中的所有用戶信息:
輸入網(wǎng)址:http://localhost:8080/all,選擇get請求方式胀蛮,點擊send∨锤疲可以看到結果如圖所示粪狼,因為此時數(shù)據(jù)庫中還沒有數(shù)據(jù)。
getAllUser - 向數(shù)據(jù)庫中添加數(shù)據(jù):
輸入網(wǎng)址:http://localhost:8080/add任岸,選擇post方式再榄,在Body中選擇form-data,輸入對應的key-value值享潜,key列輸入表的列name和age困鸥,點擊send,可以看到有json格式的數(shù)據(jù)返回剑按,也可以在數(shù)據(jù)庫中看到數(shù)據(jù)已經(jīng)插入疾就。
(因為主鍵id使用注解@GeneratedValue設置了自增,所以不必輸入id)
此時再查看http://localhost:8080/all艺蝴,可以看到數(shù)據(jù)已返回猬腰。
-
查看id=1的用戶
輸入網(wǎng)址:http://localhost:8080/all/1,選擇get方式猜敢,點擊send姑荷,結果如圖所示:
id select -
刪除id=1的用戶
輸入網(wǎng)址:http://localhost:8080/del/1盒延,選擇delete方式鼠冕,點擊send,到數(shù)據(jù)庫查看畦贸,可以看到數(shù)據(jù)庫已更新薄坏。
以id delete
??問題總結: 確認在application.properties中胶坠,
spring.datasource.driver-class-name
的值要與springboot的版本對應繁堡,以及api操作和springboot版本的對應。否則會出現(xiàn)報錯 Inferred type 'S' for type parameter 'S' is not within its bound闻牡;should extend ‘com.mysql.cj.jdbc.Driver’罩润。
如:
return girlRepository.findOne(id);
要改成:
return userRepository.findById(id).orElse(null);
- 用postman時翼馆,鏈接url地址注意要寫正確,我把
http
寫成了https
造成了錯誤严沥。
(參考http和https的區(qū)別問題(待更新)) - 用postman模擬請求時中姜,發(fā)現(xiàn)get方法返回正確數(shù)據(jù),post方法出現(xiàn)錯誤翩瓜,查看報錯信息奥溺,有一句是:Field ‘id’ doesn't have a default value骨宠,而且還在數(shù)據(jù)庫中多了一個hibernate.sequence的表相满。當時是按照參考博文的代碼來寫的立美,如果完全按照我的上述代碼寫應該不會出現(xiàn)此問題建蹄。查詢之后發(fā)現(xiàn)是主鍵的自增策略問題裕偿,需要設置@GeneratedValue(strategy = GenerationType.IDENTITY)嘿棘,而不能單單寫@GeneratedValue(參考@GeneratedValue注解(待更新))
- 在出現(xiàn)上述錯誤之后,我改了代碼鸟妙,重新啟動項目發(fā)現(xiàn)還是報錯重父,思考了一下,應該是spring.jpa.hibernate.ddl-auto=update的原因房午,使得之前的修改并沒有生效,解決方法1:刪除原數(shù)據(jù)庫中的表嗦锐,重新啟動項目;解決方法2:將update改為create萎羔,重新啟動項目。建議選擇方法1缘眶。(參考spring.jpa.hibernate.ddl-auto問題(待更新))
??疑問:為什么在UserController類中巷懈,向數(shù)據(jù)庫中添加一條數(shù)據(jù)時要new一個user慌洪,我記得springboot的優(yōu)點之一就是在于注入依賴凑保,不需要new對象啊欧引。請求大家?guī)臀医獯鹨幌轮ゴ耍俣攘酥笠策€是沒有完全理解因痛。