CRUD 代表创建,读取/查询,更新和删除。这些是持久性存储的四个基本函数。
Spring Boot提供了一个名为 CrudRepository 的接口,其中包含用于CRUD操作的方法。它在包 org.springframework.data.repository 中定义。它扩展了Spring Data Repository接口。它在存储库上提供通用的Crud操作。如果要在应用程序中使用CrudRepository,则必须创建一个接口并扩展 CrudRepository 。
public interface CrudRepository<T,ID> extends Repository<T,ID>
在哪里,
例如:
public interface StudentRepository extends CrudRepository<Student, Integer> { }
在上面的示例中,无涯教程创建了一个名为 StudentRepository 的接口,该接口扩展了CrudRepository。其中 Student 是要管理的存储库,而 Integer 是Student存储库中定义的ID类型。
JpaRepository提供了与JPA相关的方法,它在包 org.springframework.data.jpa.repository中定义。 JpaRepository扩展了 CrudRepository 和 PagingAndSortingRepository。
例如:
public interface BookDAO extends JpaRepository { }
CrudRepository | JpaRepository |
---|---|
CrudRepository没有提供任何用于分页和排序的方法。 | JpaRepository扩展了PagingAndSortingRepository。它提供了实现分页的所有方法。 |
它用作标记接口。 | JpaRepository扩展了 CrudRepository 和 PagingAndSortingRepository 。 |
仅提供CRUD函数。例如 findById(),findAll(),等。 | 它提供了一些额外的方法,以及PagingAndSortingRepository和CrudRepository的方法。例如, flush(),deleteInBatch()。 |
在不需要JpaRepository和PagingAndSortingRepository提供的函数时使用。 | 当要在应用程序中实现分页和排序函数时使用。 |
让无涯教程设置一个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 文件中,并将其下载到本地系统。
步骤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类中,执行了以下操作:
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 ListgetAllBooks() { 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
创建所有类和包之后,项目目录如下所示。
现在,无涯教程将运行该应用程序。
步骤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); } }
步骤19 - 打开Postman并执行以下操作:
{ "bookid": "5433", "bookname": "Core and Advance Java", "author": "R. Nageswara Rao", "price": "800" }
成功执行请求后,它会显示状态: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。点击连接按钮,如下所示。
单击连接按钮后,无涯教程将在数据库中看到 Books 表,如下所示。
步骤21 - 单击 Books 表,然后单击 Run 按钮。该表显示了插入到正文中的数据。
第22步 - 打开Postman,并发送带有URL http://localhost:8080/books的 GET 请求。它返回已插入数据库中的数据。
发送一个URL为http:// localhost:8080/book/{bookid}的 GET 请求。已经指定了 bookid 6830 。它返回ID为6830的书的详细信息。
同样,也可以发送 DELETE 请求以删除记录。假设要删除ID为 5433 的图书记录。
选择 DELETE 方法并调用URL http:// localhost:8080/book/5433。再次在H2控制台中执行 Select 查询。发现ID为 5433 的图书已从数据库中删除。
同样,也可以通过发送 PUT 请求来更新记录。更新ID为 6321 的图书的价格。
{ "bookid": "6321", "bookname": "Data Structures and Algorithms in Java", "author": "Robert Lafore", "price": "500" }
现在,移至H2控制台,查看更改是否已反映。无涯教程看到这本书的价格已更改,如下所示。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)