使用 Java Spring Boot 的基础 CRUD

发布: (2025年12月13日 GMT+8 20:07)
3 min read
原文: Dev.to

Source: Dev.to

什么是 Spring Boot

Spring Boot 是一个 Java 框架,帮助你轻松构建 Web 和后端应用。它为你处理大部分的设置和配置,让你可以专注于编写业务代码,而无需管理繁琐的配置。

入门指南

  1. 在系统上安装 Java(JDK)。
  2. 前往 Spring Initializr 创建一个新的 Spring Boot 项目。选择项目名称、Java 版本并添加所需的依赖。点击 Generate 并解压生成的压缩包。
  3. 在 IDE 中打开生成的文件夹(例如 IntelliJ IDEA —— 从官方站点下载 Community 版)。

项目结构概览

一个典型的处理 CRUD 操作的 Spring Boot 应用遵循分层架构:

层级描述
Entity / Model表示数据库表的 Java 类(例如 UserProduct)。
Repository直接与数据库交互的接口(Spring Data JPA)。
Service包含业务逻辑并使用 Repository 进行数据操作。
Controller接收 HTTP 请求,委托给 Service,并返回响应。

CRUD 操作映射

操作功能HTTP 方法Spring 注解Repository 方法目的
Create插入数据POST@PostMappingsave(entity)向数据库添加一条新记录。
Read检索数据GET@GetMappingfindAll()findById(id)获取单条或全部记录。
Update修改数据PUT@PutMappingsave(entity)更改已有记录的数据。
Delete删除数据DELETE@DeleteMappingdeleteById(id)永久删除一条记录。

1. 创建(C)

目标: 将一个新实体(例如新学生)保存到 MySQL 数据库。

Controller

@PostMapping("/addStudent")
public String postDetails(@RequestBody StudentEntity studentEntity) {
    System.out.println("Student entity received: " + studentEntity);
    studentService.saveDetails(studentEntity);
    return "ADDED TO TABLE SUCCESSFULLY";
}

Service

public StudentEntity saveDetails(StudentEntity studentEntity) {
    return studentRepository.save(studentEntity);
}

结果: 在对应的 MySQL 表中插入一行新记录。

2. 读取(R)

目标: 从数据库中获取数据。

读取全部

@GetMapping("/getStudent")
public List getDetails() {
    return studentService.getAllDetails();
}

按 ID 读取

@GetMapping("/getStudent/{id}")
public StudentEntity getDetailsById(@PathVariable int id) {
    return studentService.getAllDetailsById(id);
}

Service 方法

// Get all details
public List getAllDetails() {
    return studentRepository.findAll();
}

// Get detail by ID
public StudentEntity getAllDetailsById(int id) {
    return studentRepository.findById(id).orElse(null);
}

3. 更新(U)

目标: 修改数据库中已有的实体。

Controller

@PostMapping("/updateStudent")
public StudentEntity updateDetails(@RequestBody StudentEntity studentEntity) {
    return studentService.updateAllDetail(studentEntity);
}

Service

public StudentEntity updateAllDetail(StudentEntity studentEntity) {
    StudentEntity existing = studentRepository.findById(studentEntity.getId()).orElse(null);
    if (existing != null) {
        existing.setMark(studentEntity.getMark());
        existing.setName(studentEntity.getName());
        studentRepository.save(existing);
        return existing;
    }
    return null;
}

4. 删除(D)

目标: 从数据库中删除记录。

Controller

@DeleteMapping("/deleteStudent/{id}")
public String deleteStudent(@PathVariable int id) {
    if (studentService.deleteStudentById(id))
        return "Deleted Successfully";
    else
        return "Can't Delete";
}

Service

public boolean deleteStudentById(int id) {
    studentRepository.deleteById(id);
    return true;
}

结果: 对应记录被永久从 MySQL 表中删除。

配置数据库

src/main/resources/application.properties 文件中创建或编辑 MySQL 连接信息,例如:

spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

这些设置告诉 Spring Boot 如何连接 MySQL 并配置 JPA 的行为。

Back to Blog

相关文章

阅读更多 »

面向初学者的 Java 后端项目

Forem 标志 https://media2.dev.to/dynamic/image/width=65,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%...