English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
CRUD Represents Creation, reading/Retrieval, updateand DeleteThese are the four basic functions of persistent storage.
CRUD operations can be defined as user interface conventions, which allow viewing, searching, and modifying information through computer-based forms and reports. HTTP action verbsStandardized usage. HTTP has some important verbs.
POST: Create new resource GET: Read resource PUT: Update existing resource DELETE: Delete resource
In a database, each of these operations directly maps to a series of commands. However, their relationship with RESTful APIs is slightly more complex.
Create operation: It executes an INSERT statement to create new records. Read operation: It reads table records based on input parameters. Update operation: It executes an update statement on the table. It bases on input parameters. Delete operation: It will delete the specified rows in the table. It also bases on input parameters.
CRUD operations are the foundation of the most dynamic websites. Therefore, we should understand CRUD and HTTP Action verbsdistinguish them.
Suppose we want to Createa new record, we should use the HTTP operation verb POST . To Updatea record, we should use PUT verb. Similarly, if you want to Deleterecords, then you should use DELETE verbs. Through CRUD operations, users and administrators have the right to retrieve, create, edit, and delete records online.
We have many options for executing CRUD operations. One of the most effective choices is to create a set of stored procedures in SQL to perform the operations.
CRUD operations refer to all major functions implemented in a relational database application. Each letter of CRUD can be mapped to an SQL statement and an HTTP method.
operations | SQL | HTTP verbs | RESTful Web services |
Create | INSERT | PUT/POST | POST |
Read | SELECT | GET | GET |
Update | UPDATE | PUT/POST/PATCH | PUT |
Delete | Delete | Delete | Delete |
Spring Boot provides an interface named CrudRepository interface, which contains methods for CRUD operations. It is in the package org.springframework.data.repository defined. It extends the Spring Data repositoryinterface. It provides generic CRUD operations on the repository. If you want to use CrudRepository in your application, you must create an interface and extend CrudRepository .
syntax
public interface CrudRepository<T,ID> extends Repository<T,ID>
wherein
T is the domain type managed by the repository. ID is the ID type of the entity managed by the repository.
For example:
public interface StudentRepository extends CrudRepository<Student, Integer> { }
In the above example, we created an application named StudentRepository The interface, which extends CrudRepository. Among them Student Is the repository to be managed, and Integer Is the ID type defined in the Student repository.
JpaRepository provides methods related to JPA, such as refresh, persistence context, and batch deletion of a record. It is in the package Defined in org.springframework.data.jpa.repository. JpaRepository extends CrudRepository and PagingAndSortingRepository.
For example:
public interface BookDAO extends JpaRepository { }
These interfaces allow Spring to find the repository interface and create a proxy object for it. It provides methods that allow us to perform some common operations. We can also define custom methods.
CrudRepository | JpaRepository |
CrudRepository does not provide any methods for pagination and sorting. | JpaRepository extends PagingAndSortingRepository. It provides all the methods to implement pagination. |
It is used asAnnotationinterface. | JpaRepository extends CrudRepository and PagingAndSortingRepository . |
It only provides CRUD functions. For example findById(), findAll()etc. | It provides some additional methods as well as the methods of PagingAndSortingRepository and CrudRepository. For example, flush(), deleteInBatch(). |
It is used when we do not need the features provided by JpaRepository and PagingAndSortingRepository. | It is used when we want to implement pagination and sorting features in the application. |
Let's set up a Spring Boot application and perform CRUD operations.
steps1: Open Spring Initializr http://start.spring.io .
steps2: Select the Spring Boot version 2.3.0.M1.
steps2: GroupName. We provide com.w3codebox.
steps3: Provide Artifact ID. We provide spring-boot-crud-operation.
steps5: Add dependencies Spring Web, Spring Data JPA,and H2database.
steps6: click Generate (Generate) button. When we click the 'Generate' button, it will package the specifications in Jar the file and download it to the local system.
steps7: Extract Jar file and paste it into the STS workspace.
steps8: MoveProject folder import STS.
File-> Import-> Existing Maven project-> Browse-> Select folder spring-boot-crud-operation-> Complete
Importing may take some time.
steps9: Create a directory named com.w3codebox.model The package. Folder src/main/java.
steps10: In the package com.w3Create the class in codebox.model. We created a named Books class. In the 'Books' class, we performed the following operations:
Define four variables bookid, bookname, author,and Generate Getter and Setters.
Right-click on the file-> Source-> Generate Getters and Setters. Using annotations @Entitymarks the class asEntity. Using annotations @TableMark this class as Table Name. Using annotations @Column Define each variable as Column .
Books.java
package com.w3codebox.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; } }
steps11: In src/main/Create a file named com.w3codebox.controller package.
steps12: In the package com.w3Create a Controller class in codebox.controller. We created a named BooksController controller class. In the BooksController class, we have completed the following operations:
Using annotations @RestControllermarks the class as RestController . Using annotations @Autowired Automatic annotation BooksService class. Define the following methods: getAllBooks(): . It returns a list of all books. getBooks(): It returns the detailed information of the book specified in the path variable. By using the @PathVariable annotation, we have passed bookid as a parameter. The annotation indicates that the method parameter should be bound to the URI template variable. deleteeBook(): It will delete the specific book specified in the path variable. saveBook(): Save the detailed information of the book. The @RequestBody annotation indicates that the method parameter should be bound to the body of the web request. update(): This method updates a record. We must specify the record to be updated in the body to achieve the same purpose. We used the @RequestBody annotation for this.
BooksController.java
package com.w3codebox.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.w3codebox.model.Books; import com.w3codebox.service.BooksService; //Mark the class as Controller @RestController public class BooksController { //Automatically assemble the BooksService class @Autowired BooksService booksService; //Create a get mapping to retrieve all detailed information of books from the database @GetMapping("/book) private List<Books> getAllBooks() { return booksService.getAllBooks(); } //Create a get mapping to retrieve detailed information of a specific book @GetMapping("/book/{bookid}) private Books getBooks(@PathVariable("bookid") int bookid) { return booksService.getBooksById(bookid); } //Create a mapping to delete a specified book @DeleteMapping("/book/{bookid}) private void deleteBook(@PathVariable("bookid") int bookid) { booksService.delete(bookid); } //Create a post mapping to publish detailed information of books in the database @PostMapping("/books") private int saveBook(@RequestBody Books books) { booksService.saveOrUpdate(books); return books.getBookid(); } //Create a put mapping to update the detailed information of books @PutMapping("}}/books") private Books update(@RequestBody Books books) { booksService.saveOrUpdate(books); return books; } }
steps13: in the folder src/main/java create a name of com.w3codebox.service package.
steps14: Create a Service In the package com.w3A class named was created in codebox.service BooksService service class.
BooksService.java
package com.w3codebox.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.w3codebox.model.Books; import com.w3codebox.repository.BooksRepository; //Define business logic @Service public class BooksService { @Autowired BooksRepository booksRepository; //Use the cruddrepository's findAll() method to retrieve all book records public List<Books> getAllBooks() { List<Books> books = new ArrayList<Books>(); booksRepository.findAll().forEach(books1 -> books.add(books1)); return books; } //By using the cruddrepository's findById() method to retrieve a specific record public Books getBooksById(int id) { return booksRepository.findById(id).get(); } //Use the CrudRepository's save() method to save a specific record public void saveOrUpdate(Books books) { booksRepository.save(books); } //Use the CrudRepository's deleteById() method to delete a specific record public void delete(int id) { booksRepository.deleteById(id); } //Update the record public void update(Books books, int bookid) { booksRepository.save(books); } }
steps15: in the folder src/main/java create a name of com.w3codebox.repository package.
the16step: Create a repositoryinterface. We have a package com.w3a named created in codebox.repository BooksRepository the repository interface. it extends Crud repositoryinterface.
BooksRepository.java
package com.w3codebox.repository; import org.springframework.data.repository.CrudRepository; import com.w3codebox.model.Books; //repository that extends CrudRepository public interface BooksRepository extends CrudRepository<Books, Integer> { }
Now, we will application.properties Configure the data source in the file URL, driver class name, usernameand Password.
steps17: open application.properties file and configure the following 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 consolespring.h2.console.enabled=true
After creating all the classes and packages, the project directory is as follows.
Now we will run the application.
steps18: open SpringBootCrudOperationApplication.java file and run it as a Java application.
SpringBootCrudOperationApplication.java
package com.w3codebox; 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); } }
steps19: open Postmanand perform the following operations:
Select POST Call the URL http://localhost:8080/books. SelectBody Select content type JSON(application/json). Insert the following data into the body:
{ "bookid": "5433", "bookname": "Core and Advance Java", "author": "R. Nageswara Rao", "price": "800" }
ClickSend
After the request is successfully executed, it will display Status: 200 OK . This means the record has been successfully inserted into the database.
Similarly, we have inserted the following data.
{"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" }
Let's access H2console to view the data.
steps20: open a browser and call the URL http://localhost:8080/h2-console. Click Connect button, as shown below.
click connectionbutton, and we will see in the database Books table, as shown below.
steps21: click Books table, and then click runbutton. This table displays the data we have inserted into the text.
steps22: open Postmanand send the URL as http://localhost:8080/books' section GET request. It returns the data we inserted into the database.
We send the request at URL http://localhost:8080/book/{bookid} send GET request. We specified bookid 6830 . It returns the ID6830 detailed information of the book.
Similarly, we can also send DELETE request to delete the record. Assume we want to delete the record with ID 5433 the book record.
Select DELETE method and call the URL http://localhost:8080/book/5433. Again in H2execute in the console Select query. We found that the ID 5433 the book has been deleted from the database.
Similarly, we can also send PUT request to update the record. Let's update the record with ID 6321 the price of the book.
Select PUT In the request body, paste the record to be updated and make changes. In this example, we want to update the record with ID6321of the book records. In the following records, we changed the price of the book.
{ "bookid": "6321", "bookname": "Data Structures and Algorithms in Java", "author": "Robert Lafore", "price": "500" }
ClickSend
Now, move to H2Console, check if the changes have been reflected. We see that the price of this book has changed as follows.