📜  Spring Boot – CRUD 操作

📅  最后修改于: 2022-05-13 01:55:17.325000             🧑  作者: Mango

Spring Boot – CRUD 操作

CRUD 代表创建、读取/检索、更新和删除,这是我们在持久性存储上执行的四个基本操作。 CRUD 是面向数据和 HTTP 方法的标准化使用。 HTTP 有一些方法可以用作 CRUD 操作,并且请注意,从开发的角度来看,它们在编程中非常重要,这也有助于我们更好地联系 Web 开发,并在处理数据库时帮助我们。因此,标准的 CRUD 操作如下:

  • POST : 创建一个新资源
  • GET :读取/检索资源
  • PUT :更新现有资源
  • DELETE :删除资源

顾名思义

  • CREATE 操作:执行 INSERT 语句以创建新记录。
  • READ 操作:根据输入参数读取表记录。
  • 更新操作:对表执行更新语句。它基于输入参数。
  • DELETE 操作:删除表中的指定行。它也基于输入参数。

因此,在本文中,我们将通过创建 Spring Boot 应用程序并使用 H2 数据库来执行一些基本的 CRUD 操作。所以这里简单解释一下什么是Spring Boot和什么是H2数据库。

弹簧靴

Spring Boot 建立在 Spring 之上,包含了 Spring 的所有特性。并且现在正成为开发人员的最爱,因为它是一个快速的生产就绪环境,使开发人员能够直接专注于逻辑,而不是为配置和设置而苦恼。 Spring Boot 是一个基于微服务的框架,在其中制作可用于生产的应用程序只需要很少的时间。

H2 数据库

H2 是一个用Java编写的关系数据库管理系统。它可以嵌入到Java应用程序中或以客户端-服务器模式运行。 H2的主要特点是:

  • 非常快速的开源 JDBC API
  • 嵌入式和服务器模式;内存数据库
  • 基于浏览器的控制台应用程序
  • 占用空间小:大约 2.5 MB jar 文件大小

Spring Boot CrudRepository

Spring Boot 中有一个名为 CrudRepository 的接口,其中包含用于 CRUD 操作的方法。它在存储库上提供通用的 Crud 操作。它在包org.springframework.data.repository中定义,它扩展了 Spring Data Repository接口。如果有人想在 Spring Boot 应用程序中使用 CrudRepository,他/她必须创建一个接口并扩展 CrudRepository 接口。

插图:

public interface DepartmentRepository extends CrudRepository { }

在哪里:

  • Department :存储库管理的域类型(通常是实体/模型类名称)
  • Long :存储库管理的实体的 id 类型(通常是在 Entity/Model 类中创建的 @Id 的包装类)

例子:

第一步:参考这篇文章如何使用 IntelliJ IDEA 创建 Spring Boot 项目并创建一个 Spring Boot 项目。

第二步:添加以下依赖

  • 春季网络
  • H2 数据库
  • 龙目岛
  • 春季数据 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
        
 
        
            com.h2database
            h2
            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.java File
 
// Importing required package modules
package com.amiya.springbootdemoproject.entity;
 
// Importing required classes
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
 
@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
package com.amiya.springbootdemoproject.repository;
 
import com.amiya.springbootdemoproject.entity.Department;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
 
@Repository
public interface DepartmentRepository extends CrudRepository {
     
}


Java
// Java Program to Illustrate DepartmentService.java File
 
// Importing packages
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
// Importing required classes
import java.util.List;
 
// Class
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.java
// File
 
// Importing required packages
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 implementing DepartmentService 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.java File
 
// Importing packages modules
package com.amiya.springbootdemoproject.controller;
 
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.service.DepartmentService;
import java.util.List;
// Importing required classes
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
// Annotation
@RestController
// Class
public class DepartmentController {
 
    @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 个包,然后在这些包中创建一些类和接口,如下图所示:

  • 实体
  • 存储库
  • 服务
  • 控制器

第 4 步:在实体包内

在 Department 内部创建一个简单的 POJO 类。 Java文件。

例子

Java

// Java Program to Illustrate Department.java File
 
// Importing required package modules
package com.amiya.springbootdemoproject.entity;
 
// Importing required classes
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
 
@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。正如我们上面讨论的那样,这个接口将扩展 CrudRepository。下面是DepartmentRepository 的代码。Java

例子

Java

package com.amiya.springbootdemoproject.repository;
 
import com.amiya.springbootdemoproject.entity.Department;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
 
@Repository
public interface DepartmentRepository extends CrudRepository {
     
}

第 6 步:在服务包内

在包中创建一个名为DepartmentService的接口和一个名为DepartmentServiceImpl的类。

示例 1

Java

// Java Program to Illustrate DepartmentService.java File
 
// Importing packages
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
// Importing required classes
import java.util.List;
 
// Class
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);
}

下面是DepartmentServiceImpl 的代码。Java

示例 2

Java

// Java Program to Illustrate DepartmentServiceImpl.java
// File
 
// Importing required packages
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 implementing DepartmentService 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.java File
 
// Importing packages modules
package com.amiya.springbootdemoproject.controller;
 
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.service.DepartmentService;
import java.util.List;
// Importing required classes
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
// Annotation
@RestController
// Class
public class DepartmentController {
 
    @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

# H2 Database
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:dcbapp
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

现在运行您的应用程序,让我们在 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

最后,H2 数据库如下图所示: