Whenever there is request to delete data from table we can use HTTP DELETE method. it indicates that it wants to delete the resource identified by the given URI. then processes the request and, if successful, removes the specified resource.
We can also delete record using Http Get, Http Post method.
DELETE (D)  : Last Operation of Spring Boot CRUD Operation. Its is mainly used to remove the record from data bases.
Step 1: Create package with controller with your base package, then create java file BookController.java and then put below code in controller, here we have created deleteBook() method .
package com.techbug.techbug.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.techbug.techbug.service.BookService;

@RestController
public class BookController {

@Autowired
private BookService bookService;

@DeleteMapping(value = "/deletebook")
public String deleteBook(@RequestParam Long bookId) {
return bookService.deleteBook(bookId);
 }
}

 

Step 2: Now we will use JAPRepository deleteById(id) method. It will delete row which id is matching with input id.
package com.techbug.techbug.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.techbug.techbug.entity.Book;
import com.techbug.techbug.repository.BookRepository;
import com.techbug.techbug.vo.BookVO;

@Service
public class BookService {

@Autowired
private BookRepository bookRepository;

public String deleteBook(Long bookId) {
   bookRepository.deleteById(bookId);
   return "Book Deleted Successfully !!";
 }
}

 

Now Start Java Spring Boot Application and hit end point from postman, http://localhost:9080/deletebook?bookId=1 here we are passing bookId as @RequestParam so id can be directly passed in url. Before hitting api lets see no of rows in table.

http delete method in spring

 

http delete method from postman

After Execution we see only one row available bookId 1 got deleted from table.

http delete

Happy learning.

Read Complete CRUD article here

Http Post Method with Example (Create – C)
Http Get Method with Example  (Read – R)
Http Update Method with Example (Update – U)
Http Delete Method with Example ( Delete – D)

Http

 

Leave a Reply

Your email address will not be published. Required fields are marked *