之前的篇章介紹完了 Jwt Token 的部分,接下來我們來介紹基礎簡單的一隻 Api。
在 Spring Boot 中,一般會按照三層架構來組織代碼:
如上述示例所展示的,通常項目包結構如下:
com.example.demo
├── student
│ ├── Student.java
│ ├── StudentController.java
│ ├── StudentService.java
│ ├── StudentRepository.java
│ └── StudentConfig.java
└── DemoApplication.java
那我們先建立資料表 Student
package com.example.demo.student;
import jakarta.persistence.*;
import java.time.LocalDate;
import java.time.Period;
@Entity
//@Table(name = "sss")
public class Student {
@Id
@SequenceGenerator(
name = "student_sequence",
sequenceName = "student_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "student_sequence"
)
private Long id;
private String name;
private String email;
private LocalDate dob;
@Transient
private Integer age;
public Student(Long id,
String name,
String email,
LocalDate dob) {
this.id = id;
this.name = name;
this.email = email;
this.dob = dob;
}
public Student(String name, String email, LocalDate dob) {
this.name = name;
this.email = email;
this.dob = dob;
// this.age = age;
}
public Student() {
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
public Integer getAge() {
return Period.between(this.dob, LocalDate.now()).getYears();
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", dob=" + dob +
", age=" + age +
'}';
}
}