Spring Boot - CRUD操作

Spring Boot - CRUD操作 首页 / Spring Boot入门教程 / Spring Boot - CRUD操作

CRUD 代表创建,读取/查询,更新删除。这些是持久性存储的四个基本函数。

标准CRUD操作

  • 创建操作 - 它执行INSERT语句以创建新记录。
  • 读取操作 - 它根据输入参数读取表记录。
  • 更新操作 - 它在表上执行一条update语句。
  • 删除操作 - 它将删除表中的指定行。

CrudRepository接口

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

public interface CrudRepository<T,ID> extends Repository<T,ID>

在哪里,

  • T   是存储库管理的域类型。
  • ID 是存储库管理的实体的ID类型。

例如:

public interface StudentRepository extends CrudRepository<Student, Integer>
{
}

在上面的示例中,无涯教程创建了一个名为 StudentRepository 的接口,该接口扩展了CrudRepository。其中 Student 是要管理的存储库,而 Integer 是Student存储库中定义的ID类型。

JpaRepository类

JpaRepository提供了与JPA相关的方法,它在包 org.springframework.data.jpa.repository中定义。 JpaRepository扩展了 CrudRepository PagingAndSortingRepository。

例如:

public interface BookDAO extends JpaRepository 
{
}
Spring Boot CRUD Operations

CrudRepository与JpaRepository

CrudRepository JpaRepository
CrudRepository没有提供任何用于分页和排序的方法。 JpaRepository扩展了PagingAndSortingRepository。它提供了实现分页的所有方法。
它用作标记接口。 JpaRepository扩展了 CrudRepository PagingAndSortingRepository
仅提供CRUD函数。例如 findById(),findAll(),等。它提供了一些额外的方法,以及PagingAndSortingRepository和CrudRepository的方法。例如, flush(),deleteInBatch()。
在不需要JpaRepository和PagingAndSortingRepository提供的函数时使用。当要在应用程序中实现分页和排序函数时使用。

CRUD 示例

让无涯教程设置一个Spring Boot应用程序并执行CRUD操作。

步骤1 - 打开Spring Initializr http://start.spring.io

步骤2 - 选择Spring Boot版本 2.3.0.M1。

步骤3 - 填写Group名称。

步骤4 - 填写Artifact ID。提供了 spring-boot-crud-operation

步骤5 - 添加依赖项Spring Web,Spring Data JPA和H2数据库。

步骤6 - 单击 Generate (生成)按钮。当无涯教程单击"Generate"按钮时,它将规格包装在 Jar 文件中,并将其下载到本地系统。

Spring Boot CRUD Operations

步骤7 - 然后将其粘贴到STS工作区中。

步骤8 - 项目文件夹导入STS。

File -> Import -> Existing Maven Projects -> Browse -> Select the folder spring-boot-crud-operation -> Finish

步骤9 - 在文件夹 src/main/java中创建一个名称为 com.learnfk.model 的软件包。

步骤10 - 在包 com.learnfk.model中创建模型类。 创建了一个名为 Books的模型类。 

    Books.java

    package com.learnfk.model;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    //mark class as an Entity 
    @Entity
    //defining class name as Table name
    @Table
    public class Books
    {
      //Defining book id as primary key
      @Id
      @Column
      private int bookid;
      @Column
      private String bookname;
      @Column
      private String author;
      @Column
      private int price;
      public int getBookid() 
      {
        return bookid;
      }
      public void setBookid(int bookid) 
      {
        this.bookid = bookid;
      }
      public String getBookname()
      {
        return bookname;
      }
      public void setBookname(String bookname) 
      {
        this.bookname = bookname;
      }
      public String getAuthor() 
      {
        return author;
      }
      public void setAuthor(String author) 
      {
        this.author = author;
      }
      public int getPrice() 
      {
        return price;
      }
      public void setPrice(int price) 
      {
        this.price = price;
      }
    }

    步骤11 - 在文件夹 src/main/java中创建一个名称为 com.learnfk.controller 的软件包。

    步骤12 - 在包 com.learnfk.controller中创建一个Controller类。 创建了一个名为 BooksController的控制器类。 在BooksController类中,执行了以下操作:

    • 通过使用注释 @RestController将类标记为 RestController 使用注释 @Autowired
    • 自动连接 BooksService 类。
    • 定义以下方法:
      • getAllBooks()  -  它返回所有书籍的列表。
      • getBooks()       -  它返回在path变量中指定的书籍详细信息。通过使用注释@PathVariable,已将bookid作为参数传递。
      • deleteBook()   -  它将删除在path变量中指定的特定书籍。
      • saveBook()       -  保存图书详细信息。注释@RequestBody表示应将方法参数绑定到Web请求的正文。
      • update()            -  该方法更新一条记录。必须在正文中指定要更新的记录。为了达到相同的目的,使用了@RequestBody注释。

    BooksController.java

    package com.learnfk.controller;
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.PutMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;
    import com.learnfk.model.Books;
    import com.learnfk.service.BooksService;
    //mark class as Controller
    @RestController
    public class BooksController 
    {
      //autowire the BooksService class
      @Autowired
      BooksService booksService;
      //creating a get mapping that retrieves all the books detail from the database 
      @GetMapping("/book")
      private List getAllBooks() 
      {
        return booksService.getAllBooks();
      }
      //creating a get mapping that retrieves the detail of a specific book
      @GetMapping("/book/{bookid}")
      private Books getBooks(@PathVariable("bookid") int bookid) 
      {
        return booksService.getBooksById(bookid);
      }
      //creating a delete mapping that deletes a specified book
      @DeleteMapping("/book/{bookid}")
      private void deleteBook(@PathVariable("bookid") int bookid) 
      {
        booksService.delete(bookid);
      }
      //creating post mapping that post the book detail in the database
      @PostMapping("/books")
      private int saveBook(@RequestBody Books books) 
      {
        booksService.saveOrUpdate(books);
        return books.getBookid();
      }
      //creating put mapping that updates the book detail 
      @PutMapping("/books")
      private Books update(@RequestBody Books books) 
      {
        booksService.saveOrUpdate(books);
        return books;
      }
    }

    步骤13 - 在文件夹 src/main/java中创建一个名称为 com.learnfk.service 的软件包。

    步骤14 - 创建一个服务类。无涯教程在包 com.learnfk.service 中创建了一个名为 BooksService 的服务类。

    BooksService.java

    package com.learnfk.service;
    import java.util.ArrayList;
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import com.learnfk.model.Books;
    import com.learnfk.repository.BooksRepository;
    //defining the business logic
    @Service
    public class BooksService 
    {
      @Autowired
      BooksRepository booksRepository;
      //getting all books record by using the method findaAll() of CrudRepository
      public List<Books> getAllBooks() 
      {
        List<Books> books = new ArrayList<Books>();
        booksRepository.findAll().forEach(books1 -> books.add(books1));
        return books;
      }
      //getting a specific record by using the method findById() of CrudRepository
      public Books getBooksById(int id) 
      {
        return booksRepository.findById(id).get();
      }
      //saving a specific record by using the method save() of CrudRepository
      public void saveOrUpdate(Books books) 
      {
        booksRepository.save(books);
      }
      //deleting a specific record by using the method deleteById() of CrudRepository
      public void delete(int id) 
      {
        booksRepository.deleteById(id);
      }
      //updating a record
      public void update(Books books, int bookid) 
      {
        booksRepository.save(books);
      }
    }

    步骤15 -  src/main/java文件夹中创建一个名称为 com.learnfk.repository 的软件包。

    步骤16 - 创建一个存储库接口。在包 com.learnfk.repository中创建了名称为 BooksRepository 的存储库接口。 

    BooksRepository.java

    package com.learnfk.repository;
    import org.springframework.data.repository.CrudRepository;
    import com.learnfk.model.Books;
    //repository that extends CrudRepository
    public interface BooksRepository extends CrudRepository
    {
    }

    现在,无涯教程将在 application.properties 文件中配置数据源 URL,驱动程序类名称,用户名密码

    步骤17 - 打开 application.properties 文件并配置以下属性。

    application.properties

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

    Note: 不要忘记启用H2控制台。

    创建所有类和包之后,项目目录如下所示。

    Spring Boot CRUD Operations

    现在,无涯教程将运行该应用程序。

    步骤18 - 打开 SpringBootCrudOperationApplication.java 文件并将其作为Java应用程序运行。

    SpringBootCrudOperationApplication.java

    package com.learnfk;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    @SpringBootApplication
    public class SpringBootCrudOperationApplication 
    {
      public static void main(String[] args) 
      {
        SpringApplication.run(SpringBootCrudOperationApplication.class, args);
      }
    }

    Note: 在接下来的步骤中,将使用其余客户端Postman。因此,请确保您的系统中已经安装了Postman应用程序。

    步骤19 - 打开Postman并执行以下操作:

    • 选择 POST
    • 调用URL http:// localhost:8080/books。
    • 选择Body
    • 选择内容类型 JSON(应用程序/ json)。
    • 插入数据。已在车身中插入以下数据:
    {
        "bookid": "5433",
        "bookname": "Core and Advance Java",
        "author": "R. Nageswara Rao",
        "price": "800"
    } 
    • 点击Send

    成功执行请求后,它会显示状态:200 OK 。这意味着记录已成功插入数据库中。

    同样,插入了以下数据。

    {
        "bookid": "0982",
        "bookname": "Programming with Java",
        "author": "E. Balagurusamy",
        "price": "350"
    } 
    {
        "bookid": "6321",
        "bookname": "Data Structures and Algorithms in Java",
        "author": "Robert Lafore",
        "price": "590"
    } 
    {
        "bookid": "5433",
        "bookname": "Effective Java",
        "author": "Joshua Bloch",
        "price": "670"
    }

    访问H2控制台以查看数据。

    步骤20 - 打开浏览器并调用URL http:// localhost:8080/h2-console。点击连接按钮,如下所示。

    Spring Boot CRUD Operations

    单击连接按钮后,无涯教程将在数据库中看到 Books 表,如下所示。

    Spring Boot CRUD Operations

    步骤21 - 单击 Books 表,然后单击 Run 按钮。该表显示了插入到正文中的数据。

    Spring Boot CRUD Operations

    第22步 - 打开Postman,并发送带有URL http://localhost:8080/books的 GET 请求。它返回已插入数据库中的数据。

    Spring Boot CRUD Operations

    发送一个URL为http:// localhost:8080/book/{bookid}的 GET 请求。已经指定了 bookid 6830 。它返回ID为6830的书的详细信息。

    Spring Boot CRUD Operations

    同样,也可以发送 DELETE 请求以删除记录。假设要删除ID为 5433 的图书记录。

    选择 DELETE 方法并调用URL http:// localhost:8080/book/5433。再次在H2控制台中执行 Select 查询。发现ID为 5433 的图书已从数据库中删除。

    Spring Boot CRUD Operations

    同样,也可以通过发送 PUT 请求来更新记录。更新ID为 6321 的图书的价格。

    • 选择 PUT
    • 在请求正文中,粘贴要更新的记录并进行更改。在本例中,要更新ID为6321的书籍的记录。在以下记录中,无涯教程更改了书籍的价格。
    {
        "bookid": "6321",
        "bookname": "Data Structures and Algorithms in Java",
        "author": "Robert Lafore",
        "price": "500"
    }
    • 点击Send

    现在,移至H2控制台,查看更改是否已反映。无涯教程看到这本书的价格已更改,如下所示。

    Spring Boot CRUD Operations

    祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

    技术教程推荐

    人工智能基础课 -〔王天一〕

    零基础学Python -〔尹会生〕

    Serverless入门课 -〔蒲松洋(秦粤)〕

    正则表达式入门课 -〔涂伟忠〕

    Spark核心原理与实战 -〔王磊〕

    体验设计案例课 -〔炒炒〕

    手把手教你玩音乐 -〔邓柯〕

    MySQL 必知必会 -〔朱晓峰〕

    快速上手C++数据结构与算法 -〔王健伟〕

    好记忆不如烂笔头。留下您的足迹吧 :)