📜  Spring Boot – CrudRepository 与示例

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

Spring Boot – CrudRepository 与示例

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

  • 它允许避免在 spring 中存在的 XML 的繁重配置
  • 它提供易于维护和创建 REST 端点
  • 它包括嵌入式 Tomcat 服务器
  • 部署非常简单,war和jar文件可以轻松部署在tomcat服务器中

更多信息请参考这篇文章:Spring Boot 简介。在本文中,我们将讨论如何使用 CrudRepository 来管理 Spring Boot 应用程序中的数据。

Crud存储库

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

句法:

public interface CrudRepository extends Repository

在哪里:

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

插图:

public interface DepartmentRepository extends CrudRepository {}

现在让我们讨论一下 CrudRepository 中可用的一些最重要的方法,如下所示:

方法一:save():保存给定的实体。使用返回的实例进行进一步的操作,因为保存操作可能已经完全改变了实体实例。

句法:

 S save(S entity)
  • 参数:实体——不能为空。
  • 返回:保存的实体;永远不会为空。
  • 抛出: IllegalArgumentException - 如果给定实体为空。

方法 2: findById():通过 id 检索实体。

句法:

Optional findById(ID id)
  • 参数: id - 不能为空。
  • 返回:具有给定 id 的实体,如果没有找到,则返回 Optional#empty()。
  • 抛出异常:如果“id”为空,则抛出IllegalArgumentException。

方法三:findAll():返回该类型的所有实例。

句法:

Iterable findAll()

返回类型:所有实体

方法四: count():返回可用实体的数量。

句法:

long count()

返回类型:实体的数量。

方法5: deleteById(): 删除具有给定 ID 的实体。

句法:

void deleteById(ID id)

参数:Id(不能为空)

抛出异常:如果给定的 id 为空,则发生 IllegalArgumentException。

例子

以下 Spring Boot 应用程序使用 CrudRepository 管理 Department 实体。数据保存在 H2 数据库中。我们使用 RESTful 控制器。

第一步:参考这篇文章如何使用 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
package com.amiya.springbootdemoproject.entity;
  
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;
  
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
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.java 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.repository.CrudRepository;
import org.springframework.stereotype.Repository;
  
// Annotation
@Repository
  
// Class
public interface DepartmentRepository
    extends CrudRepository {
}


Java
package com.amiya.springbootdemoproject.service;
  
import com.amiya.springbootdemoproject.entity.Department;
  
import java.util.List;
  
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
// Below is the code for the DepartmentServiceImpl.java file.
package com.amiya.springbootdemoproject.service;
  
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.repository.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
  
import java.util.List;
import java.util.Objects;
  
@Service
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
package com.amiya.springbootdemoproject.controller;
// Importing required classes
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.service.DepartmentService;
import java.util.List;
import javax.validation.Valid;
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 个包并在这些包中创建一些类和接口,如下图所示

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

第 4 步:在实体包内

在 Department 内部创建一个简单的 POJO 类。 Java文件。以下是部门的代码。Java

Java

package com.amiya.springbootdemoproject.entity;
  
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;
  
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Department {
  
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long departmentId;
    private String departmentName;
    private String departmentAddress;
    private String departmentCode;
}

第 5 步:在存储库包中

创建一个简单的接口并将接口命名为 DepartmentRepository。正如我们上面讨论的那样,这个接口将扩展CrudRepository

Java

// Java Program to Illustrate DepartmentRepository.java 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.repository.CrudRepository;
import org.springframework.stereotype.Repository;
  
// Annotation
@Repository
  
// Class
public interface DepartmentRepository
    extends CrudRepository {
}

第 6 步:在服务包内

在包中创建一个名为DepartmentService的接口和一个名为DepartmentServiceImpl的类。下面是DepartmentService 的代码。 Java文件。

示例 1-A

Java

package com.amiya.springbootdemoproject.service;
  
import com.amiya.springbootdemoproject.entity.Department;
  
import java.util.List;
  
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

// Below is the code for the DepartmentServiceImpl.java file.
package com.amiya.springbootdemoproject.service;
  
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.repository.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
  
import java.util.List;
import java.util.Objects;
  
@Service
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
package com.amiya.springbootdemoproject.controller;
// Importing required classes
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.service.DepartmentService;
import java.util.List;
import javax.validation.Valid;
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

# 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 数据库如下图所示