Spring Boot – 使用 MySQL 数据库的 CRUD 操作
CRUD 代表创建、读取/检索、更新和删除,这是我们在持久性存储上执行的四个基本操作。 CRUD 是面向数据和 HTTP 方法的标准化使用。 HTTP 有一些方法可以用作 CRUD 操作,并且请注意,从开发的角度来看,它们在编程中非常重要,这也有助于我们更好地联系 Web 开发,并在处理数据库时帮助我们。
因此,标准的 CRUD 操作如下:
- POST : 创建一个新资源
- GET :读取/检索资源
- PUT :更新现有资源
- DELETE :删除资源
顾名思义
- CREATE 操作:执行 INSERT 语句以创建新记录。
- READ 操作:根据输入参数读取表记录。
- 更新操作:对表执行更新语句。它基于输入参数。
- DELETE 操作:删除表中的指定行。它也基于输入参数。
因此,在本文中,我们将通过创建 Spring Boot 应用程序并使用 MySQL 数据库来执行一些基本的 CRUD 操作。所以这里简单解释一下什么是Spring Boot和什么是MySQL数据库。
弹簧靴
Spring Boot 建立在 Spring 之上,包含了 Spring 的所有特性。并且现在正成为开发人员的最爱,因为它是一个快速的生产就绪环境,使开发人员能够直接专注于逻辑,而不是为配置和设置而苦恼。 Spring Boot 是一个基于微服务的框架,在其中制作可用于生产的应用程序只需要很少的时间。
MySQL 数据库
MySQL 是一个 基于 SQL(结构化查询语言)的 RDBMS(关系数据库管理系统)是用于访问和管理数据库中记录的流行语言。 MySQL 是 GNU 许可下的开源和免费软件。它由 Oracle 公司提供支持。 MySQL 数据库中的数据存储在表中。表是相关数据的集合,由列和行组成。下面列出了 MySQL 的一些特性:
- 它是在网络上使用的数据库系统
- 它在服务器上运行
- 它是小型和大型应用的理想选择
- 它非常快速、可靠且易于使用
- 它使用标准 SQL
- 它可以免费下载和使用
因此,要使用 Spring Boot 应用程序连接 MySQL DB 并执行 CRUD 操作,我们只需在 application.properties 文件中配置它,如下所示:
# Configuration for MySQL Database
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url = jdbc:mysql://localhost:3306/schooldb
(Datasource URL of your DB and "schooldb", here is your schema name)
spring.datasource.username=amiya559 (Your MySQL Workbench user name)
spring.datasource.password=password.123 (Your MySQL Workbench password)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql:true
JPA 存储库
JpaRepository 是 Repository 的JPA(Java Persistence API)特定扩展。它包含CrudRepository 和 PagingAndSortingRepository的完整 API。因此它包含用于基本 CRUD 操作的 API 以及用于分页和排序的 API。
句法:
public interface JpaRepository extends PagingAndSortingRepository, QueryByExampleExecutor
在哪里
- T:存储库管理的域类型(通常是实体/模型类名)
- ID:存储库管理的实体的 ID 类型(通常是在 Entity/Model 类中创建的 @Id 的包装类)
插图:
public interface DepartmentRepository extends JpaRepository {}
示例:我们将拥有一个使用 JpaRepository 管理部门实体的 Spring Boot 应用程序。数据保存在 MySQL 数据库中。我们使用 RESTful 控制器。
第 1 步:使用 IntelliJ 创建一个 Spring Boot 项目
步骤 2:添加以下依赖项,如下所示:
- 春季网络
- MySQL 数据库
- 龙目岛
- 春季数据 JPA
下面是pom.xml文件的完整代码。
XML
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.5.5
com.amiya
Spring-Boot-Demo-Project
1.0.0-SNAPSHOT
Spring-Boot-Demo-Project
Demo project for Spring Boot
11
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-devtools
runtime
true
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok
Java
// Java Program to Illustrate Department File
// Importing package module to code fragment
package com.amiya.springbootdemoproject.entity;
// Importing required classes
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
// Annotations
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
// Class
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long departmentId;
private String departmentName;
private String departmentAddress;
private String departmentCode;
}
Java
// Java Program to Illustrate DepartmentRepository File
// Importing package module to this code
package com.amiya.springbootdemoproject.repository;
// Importing required classes
import com.amiya.springbootdemoproject.entity.Department;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
// Annotation
@Repository
// Interface
public interface DepartmentRepository
extends JpaRepository {
}
Java
// Java Program to Illustrate DepartmentService File
// Importing package to this code fragment
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
// Importing required classes
import java.util.List;
// Interface
public interface DepartmentService {
// Save operation
Department saveDepartment(Department department);
// Read operation
List fetchDepartmentList();
// Update operation
Department updateDepartment(Department department,
Long departmentId);
// Delete operation
void deleteDepartmentById(Long departmentId);
}
Java
// Java Program to Illustrate DepartmentServiceImpl File
// Importing package module to this code
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.repository.DepartmentRepository;
// Importing required classes
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
// Annotation
@Service
// Class
public class DepartmentServiceImpl
implements DepartmentService {
@Autowired
private DepartmentRepository departmentRepository;
// Save operation
@Override
public Department saveDepartment(Department department)
{
return departmentRepository.save(department);
}
// Read operation
@Override public List fetchDepartmentList()
{
return (List)
departmentRepository.findAll();
}
// Update operation
@Override
public Department
updateDepartment(Department department,
Long departmentId)
{
Department depDB
= departmentRepository.findById(departmentId)
.get();
if (Objects.nonNull(department.getDepartmentName())
&& !"".equalsIgnoreCase(
department.getDepartmentName())) {
depDB.setDepartmentName(
department.getDepartmentName());
}
if (Objects.nonNull(
department.getDepartmentAddress())
&& !"".equalsIgnoreCase(
department.getDepartmentAddress())) {
depDB.setDepartmentAddress(
department.getDepartmentAddress());
}
if (Objects.nonNull(department.getDepartmentCode())
&& !"".equalsIgnoreCase(
department.getDepartmentCode())) {
depDB.setDepartmentCode(
department.getDepartmentCode());
}
return departmentRepository.save(depDB);
}
// Delete operation
@Override
public void deleteDepartmentById(Long departmentId)
{
departmentRepository.deleteById(departmentId);
}
}
Java
// Java Program to Illustrate DepartmentController File
// Importing package module to this code
package com.amiya.springbootdemoproject.controller;
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.service.DepartmentService;
import java.util.List;
import javax.validation.Valid;
// Importing required classes
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
// Annotation
@RestController
// Class
public class DepartmentController {
// Annotation
@Autowired private DepartmentService departmentService;
// Save operation
@PostMapping("/departments")
public Department saveDepartment(
@Valid @RequestBody Department department)
{
return departmentService.saveDepartment(department);
}
// Read operation
@GetMapping("/departments")
public List fetchDepartmentList()
{
return departmentService.fetchDepartmentList();
}
// Update operation
@PutMapping("/departments/{id}")
public Department
updateDepartment(@RequestBody Department department,
@PathVariable("id") Long departmentId)
{
return departmentService.updateDepartment(
department, departmentId);
}
// Delete operation
@DeleteMapping("/departments/{id}")
public String deleteDepartmentById(@PathVariable("id")
Long departmentId)
{
departmentService.deleteDepartmentById(
departmentId);
return "Deleted Successfully";
}
}
第 3 步:创建列出的 4 个包,并在这些包中创建一些类和接口,如下图所示:
- 实体
- 存储库
- 服务
- 控制器
Note:
- Green Rounded Icon ‘I’ Buttons are Interface
- Blue Rounded Icon ‘C’ Buttons are Classes
第 4 步:在实体包内
它是通过在 Department 中创建一个简单的 POJO 类来完成的。 Java文件。
Java
// Java Program to Illustrate Department File
// Importing package module to code fragment
package com.amiya.springbootdemoproject.entity;
// Importing required classes
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
// Annotations
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
// Class
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long departmentId;
private String departmentName;
private String departmentAddress;
private String departmentCode;
}
第 5 步:在存储库包中
创建一个简单的接口并将接口命名为 DepartmentRepository。正如我们上面讨论的那样,这个接口将扩展JpaRepository 。
例子
Java
// Java Program to Illustrate DepartmentRepository File
// Importing package module to this code
package com.amiya.springbootdemoproject.repository;
// Importing required classes
import com.amiya.springbootdemoproject.entity.Department;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
// Annotation
@Repository
// Interface
public interface DepartmentRepository
extends JpaRepository {
}
第 6 步:在服务包内
示例 1-A在包中创建一个名为DepartmentService的接口和一个名为DepartmentServiceImpl的类。
Java
// Java Program to Illustrate DepartmentService File
// Importing package to this code fragment
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
// Importing required classes
import java.util.List;
// Interface
public interface DepartmentService {
// Save operation
Department saveDepartment(Department department);
// Read operation
List fetchDepartmentList();
// Update operation
Department updateDepartment(Department department,
Long departmentId);
// Delete operation
void deleteDepartmentById(Long departmentId);
}
示例 1-B
Java
// Java Program to Illustrate DepartmentServiceImpl File
// Importing package module to this code
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.repository.DepartmentRepository;
// Importing required classes
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
// Annotation
@Service
// Class
public class DepartmentServiceImpl
implements DepartmentService {
@Autowired
private DepartmentRepository departmentRepository;
// Save operation
@Override
public Department saveDepartment(Department department)
{
return departmentRepository.save(department);
}
// Read operation
@Override public List fetchDepartmentList()
{
return (List)
departmentRepository.findAll();
}
// Update operation
@Override
public Department
updateDepartment(Department department,
Long departmentId)
{
Department depDB
= departmentRepository.findById(departmentId)
.get();
if (Objects.nonNull(department.getDepartmentName())
&& !"".equalsIgnoreCase(
department.getDepartmentName())) {
depDB.setDepartmentName(
department.getDepartmentName());
}
if (Objects.nonNull(
department.getDepartmentAddress())
&& !"".equalsIgnoreCase(
department.getDepartmentAddress())) {
depDB.setDepartmentAddress(
department.getDepartmentAddress());
}
if (Objects.nonNull(department.getDepartmentCode())
&& !"".equalsIgnoreCase(
department.getDepartmentCode())) {
depDB.setDepartmentCode(
department.getDepartmentCode());
}
return departmentRepository.save(depDB);
}
// Delete operation
@Override
public void deleteDepartmentById(Long departmentId)
{
departmentRepository.deleteById(departmentId);
}
}
第 7 步:在控制器包内
在包中创建一个名为DepartmentController 的类。
Java
// Java Program to Illustrate DepartmentController File
// Importing package module to this code
package com.amiya.springbootdemoproject.controller;
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.service.DepartmentService;
import java.util.List;
import javax.validation.Valid;
// Importing required classes
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
// Annotation
@RestController
// Class
public class DepartmentController {
// Annotation
@Autowired private DepartmentService departmentService;
// Save operation
@PostMapping("/departments")
public Department saveDepartment(
@Valid @RequestBody Department department)
{
return departmentService.saveDepartment(department);
}
// Read operation
@GetMapping("/departments")
public List fetchDepartmentList()
{
return departmentService.fetchDepartmentList();
}
// Update operation
@PutMapping("/departments/{id}")
public Department
updateDepartment(@RequestBody Department department,
@PathVariable("id") Long departmentId)
{
return departmentService.updateDepartment(
department, departmentId);
}
// Delete operation
@DeleteMapping("/departments/{id}")
public String deleteDepartmentById(@PathVariable("id")
Long departmentId)
{
departmentService.deleteDepartmentById(
departmentId);
return "Deleted Successfully";
}
}
第 8 步:下面是 application.properties 文件的代码
server.port=8082
# Configuration for MySQL Database
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/schooldb
spring.datasource.username=amiya559
spring.datasource.password=password.123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql:true
现在运行您的应用程序,让我们在 Postman 中测试端点并参考我们的 H2 数据库。
在 Postman 中测试端点
端点 1: POST – http://localhost:8082/departments/
端点 2: GET - http://localhost:8082/departments/
端点 3: PUT - http://localhost:8082/departments/1
端点 4:删除 - http://localhost:8082/departments/1
MySQL Workbench 将出现 如下所示: