使用 Java Spring Boot 的基础 CRUD
Source: Dev.to
什么是 Spring Boot
Spring Boot 是一个 Java 框架,帮助你轻松构建 Web 和后端应用。它为你处理大部分的设置和配置,让你可以专注于编写业务代码,而无需管理繁琐的配置。
入门指南
- 在系统上安装 Java(JDK)。
- 前往 Spring Initializr 创建一个新的 Spring Boot 项目。选择项目名称、Java 版本并添加所需的依赖。点击 Generate 并解压生成的压缩包。
- 在 IDE 中打开生成的文件夹(例如 IntelliJ IDEA —— 从官方站点下载 Community 版)。
项目结构概览
一个典型的处理 CRUD 操作的 Spring Boot 应用遵循分层架构:
| 层级 | 描述 |
|---|---|
| Entity / Model | 表示数据库表的 Java 类(例如 User、Product)。 |
| Repository | 直接与数据库交互的接口(Spring Data JPA)。 |
| Service | 包含业务逻辑并使用 Repository 进行数据操作。 |
| Controller | 接收 HTTP 请求,委托给 Service,并返回响应。 |
CRUD 操作映射
| 操作 | 功能 | HTTP 方法 | Spring 注解 | Repository 方法 | 目的 |
|---|---|---|---|---|---|
| Create | 插入数据 | POST | @PostMapping | save(entity) | 向数据库添加一条新记录。 |
| Read | 检索数据 | GET | @GetMapping | findAll()、findById(id) | 获取单条或全部记录。 |
| Update | 修改数据 | PUT | @PutMapping | save(entity) | 更改已有记录的数据。 |
| Delete | 删除数据 | DELETE | @DeleteMapping | deleteById(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 的行为。