CRUD操作引用关系数据库应用程序中实现的所有主要功能。 CRUD的每个字母都可以映射到SQL语句和HTTP方法。
操作    SQL    HTTP动词    RESTful Web服务
Create    INSERT    PUT/POST    POST
Read    SELECT    GET    GET
Update    UPDATE    PUT/POST/PATCH    PUT
Delete    Delete    Delete    Delete
Spring Boot CrudRepository
Spring Boot提供了一个名为 CrudRepository 的接口,其中包含用于CRUD操作的方法。它在包 org.springframework.data.repository 中定义。它扩展了Spring Data 存储库界面。它在存储库上提供通用的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类型。
Spring引导JpaRepository
JpaRepository提供了与JPA相关的方法,例如刷新,持久性上下文,并批量删除了一条记录。它在包 org.springframework.data.jpa.repository中定义。 JpaRepository扩展了 CrudRepository 和 PagingAndSortingRepository。
例如:
public interface BookDAO extends JpaRepository 
{
}
为什么要使用这些接口?
这些接口允许Spring查找存储库接口并为此创建代理对象。
它提供了允许我们执行一些常见操作的方法。我们还可以定义自定义方法。
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yt</groupId>
    <artifactId>mysql</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- DevTools in Spring Boot 项目热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
server.port=8089

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
package com.lidihuo.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;
    }
}
package com.lidihuo.model;

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.lidihuo.model.Books;
import com.lidihuo.model.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<Books> 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;
    }

}
package com.lidihuo.model;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lidihuo.model.Books;
import com.lidihuo.model.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);
    }

}
package com.lidihuo.model;

import org.springframework.data.repository.CrudRepository;
import com.lidihuo.model.Books;

//repository that extends CrudRepository
public interface BooksRepository extends CrudRepository<Books, Integer>
{
}
package com.lidihuo.model;

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);
    }
}

 

 

注意: 在接下来的步骤中,我们将使用rest client Postman。因此,请确保您的系统中已经安装了Postman应用程序。

打开 Postman并执行以下操作:
选择 POST
调用URL http://localhost:8089/books。
选择Body
选择内容类型 JSON(application/json)。
插入数据。我们已在主体中插入以下数据:
{
    "bookid": "5433",
    "bookname": "Core and Advance Java",
    "author": "R. Nageswara Rao",
    "price": "800"
} 
点击发送

类似地,我们插入了以下数据。
{
    "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"
}

 

 

打开浏览器并调用URL http://localhost:8089/h2-console。单击 Connect 按钮,如下所示。

 

 

单击 连接按钮后,我们将在数据库中看到 Books 表,如下所示。

 

 

打开 Postman,并发送URL为http://localhost:8089/book的 GET 请求。它返回我们插入数据库中的数据。

 

 

我们以URL http://localhost:8089/book/{bookid}发送 GET 请求。我们指定了 bookid 5433 。它返回ID为5433的书的详细信息。

 

 

同样,我们也可以发送 DELETE 请求删除记录。假设我们要删除ID为 5433 的图书记录。
选择 DELETE 方法并调用URL http://localhost:8089/书/5433。再次在H2控制台中执行 Select 查询。我们发现ID为 5433 的图书已从数据库中删除。

 

 

 

 

类似地,我们也可以通过发送 PUT 请求来更新记录。让我们更新ID为 982 的图书的价格。
选择 PUT
在请求正文中,粘贴要更新的记录并进行更改。在本例中,我们要更新ID为982的书籍的记录。在以下记录中,我们更改了书籍的价格。