iT邦幫忙

2024 iThome 鐵人賽

DAY 26
0

之前的篇章介紹完了 Jwt Token 的部分,接下來我們來介紹基礎簡單的一隻 Api。

在 Spring Boot 中,一般會按照三層架構來組織代碼:

  1. Controller 層:負責處理 HTTP 請求。
  2. Service 層:封裝業務邏輯。
  3. Repository 層:負責數據庫操作。

如上述示例所展示的,通常項目包結構如下:

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 +
                '}';
    }
}


上一篇
Day 25 Jwt Token Final
下一篇
Day 27 Spring boot Api Repository
系列文
Spring Boot微服務架構:API設計與實現30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言