SpringBoot DeleteMapping Example

DeleteMapping example to delete a customer based on the id. Here, will learn how to use @DeleteMapping annotation to handle the HTTP DELETE requests.

Will perform deleteById operation without using without database storage.

@DeleteMapping annotation is a simplified compact version of @RequestMapping(method-RequestMathod.DELETE)

  1. HTTP DELETE /api/v1/customer/deleteById/{customerId} – delete a customer by specified id.

SpringBoot provides a web tool to generate a initial bootstrap applicaiton which is Spring Initializer. If you want to learn the more about Spring initializer and how to use it to create the application visit following tutorial Create Springboot Application.

Project Strucure

pom.xml

While generating the SpringBoot project, will make sure that to add following Maven dependencies.


                    <?xml version="1.0" encoding="UTF-8"?>
                    <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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
                        <modelVersion>4.0.0</modelVersion>
                        <parent>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-starter-parent</artifactId>
                            <version>3.3.0</version>
                            <relativePath/> <!-- lookup parent from repository -->
                        </parent>
                        <groupId>com.sb.delete.mapping.example</groupId>
                        <artifactId>deletemappingexample</artifactId>
                        <version>0.0.1-SNAPSHOT</version>
                        <name>deletemappingexample</name>
                        <description>Demo project for Spring Boot</description>
                        <properties>
                            <java.version>17</java.version>
                        </properties>
                        <dependencies>
                            <dependency>
                                <groupId>org.springframework.boot</groupId>
                                <artifactId>spring-boot-starter-web</artifactId>
                            </dependency>

                            <dependency>
                                <groupId>org.projectlombok</groupId>
                                <artifactId>lombok</artifactId>
                                <optional>true</optional>
                            </dependency>
                            <dependency>
                                <groupId>org.springframework.boot</groupId>
                                <artifactId>spring-boot-starter-test</artifactId>
                                <scope>test</scope>
                            </dependency>
                        </dependencies>

                        <build>
                            <plugins>
                                <plugin>
                                    <groupId>org.springframework.boot</groupId>
                                    <artifactId>spring-boot-maven-plugin</artifactId>
                                    <configuration>
                                        <excludes>
                                            <exclude>
                                                <groupId>org.projectlombok</groupId>
                                                <artifactId>lombok</artifactId>
                                            </exclude>
                                        </excludes>
                                    </configuration>
                                </plugin>
                            </plugins>
                        </build>

                    </project>

                  

DeletemappingexampleApplication.java

                    package com.sb.delete.mapping.example;

                    import org.springframework.boot.SpringApplication;
                    import org.springframework.boot.autoconfigure.SpringBootApplication;

                    @SpringBootApplication
                    public class DeletemappingexampleApplication {

                        public static void main(String[] args) {
                            SpringApplication.run(DeletemappingexampleApplication.class, args);
                        }
                    }
                  

CustomerController.java

                    package com.sb.delete.mapping.example.controller;

                    import com.sb.delete.mapping.example.response.APIResponse;
                    import com.sb.delete.mapping.example.service.CustomerService;
                    import lombok.RequiredArgsConstructor;
                    import org.springframework.http.ResponseEntity;
                    import org.springframework.web.bind.annotation.*;

                    @RestController
                    @RequestMapping("/api/v1/customer")
                    @RequiredArgsConstructor
                    public class CustomerController {

                        private final CustomerService customerService;

                        @DeleteMapping("/deleteById/{customerId}")
                        public ResponseEntity<APIResponse> deleteByCustomerId(@PathVariable long customerId) {
                            return customerService.deleteByCustomerId(customerId);
                        }
                    }
                  

@RestController: This annotation is used to indicate that this class is a REST controller, which means it handles incoming HTTP requests and returns the corresponsing responses.
@RequestMapping: This annotation is used to specifies the base URL path for all the request mappings defined whith this controller.
@RequiredArgsConstructor: This annotation is used to generate the contructor with required arguments to enable the construtor injection in defined controller.
@DeleteMapping: This annotation is used to handle the HTTP DELETE requests matched with the given URI expression.
@PathVariable: This annotation is used to handle template variables in the request URI mapping, and set them as method parameters.
ResponseEntity: This object is used to send the HTTP response back to the client.

APIResponse.java

This we're going to use it as a common response object, will render all our responses and send back to the client.


                    package com.sb.post.mapping.example.response;

                    import lombok.*;

                    @Getter
                    @Setter
                    @NoArgsConstructor
                    @AllArgsConstructor
                    @EqualsAndHashCode
                    @Builder(toBuilder = true)
                    public class APIResponse {
                        private int errorCode;
                        private Object data;
                    }                     
                  

CustomerService.java

                    package com.sb.delete.mapping.example.service;

                    import com.sb.delete.mapping.example.response.APIResponse;
                    import org.springframework.http.ResponseEntity;

                    public interface CustomerService {
                        ResponseEntity<APIResponse> deleteByCustomerId(long customerId);
                    }
                  

CustomerServiceImpl.java

                    package com.sb.delete.mapping.example.service.impl;

                    import com.sb.delete.mapping.example.model.CustomerModel;
                    import com.sb.delete.mapping.example.response.APIResponse;
                    import com.sb.delete.mapping.example.service.CustomerService;
                    import org.springframework.http.ResponseEntity;
                    import org.springframework.stereotype.Service;

                    import java.time.LocalDate;
                    import java.util.ArrayList;
                    import java.util.List;
                    import java.util.concurrent.atomic.AtomicInteger;


                    @Service
                    public class CustomerServiceImpl implements CustomerService {

                        private static List<CustomerModel> customers = new ArrayList<>();
                        private static AtomicInteger c = new AtomicInteger(1);

                        static {
                            customers.add(new CustomerModel(c.getAndIncrement(), "testUser1", 21, "7234567811", "testuser1@gmail.com", "Bangalore", LocalDate.now()));
                            customers.add(new CustomerModel(c.getAndIncrement(), "testUser2", 22, "7234567812", "testuser2@gmail.com", "Hyderabad", LocalDate.now()));
                            customers.add(new CustomerModel(c.getAndIncrement(), "testUser3", 23, "7234567813", "testuser3@gmail.com", "Chennai", LocalDate.now()));
                            customers.add(new CustomerModel(c.getAndIncrement(), "testUser4", 24, "7234567814", "testuser4@gmail.com", "Pune", LocalDate.now()));
                        }

                        @Override
                        public ResponseEntity<APIResponse> deleteByCustomerId(long customerId) {

                            boolean isRemoved = customers.removeIf(customerModel -> customerModel.getCustomerId() == customerId);

                            if (isRemoved) {
                                return ResponseEntity.ok(
                                        APIResponse.builder()
                                                .errorCode(0)
                                                .data("Successfully Removed")
                                                .build()
                                );
                            } else {
                                return ResponseEntity.ok(
                                        APIResponse.builder()
                                                .errorCode(999)
                                                .data("Customer is not available")
                                                .build()
                                );
                            }
                        }
                    }
               
                  

CustomerModel.java

                    package com.sb.post.mapping.example.model;

                    import lombok.*;

                    import java.time.LocalDate;

                    @Getter
                    @Setter
                    @NoArgsConstructor
                    @AllArgsConstructor
                    @EqualsAndHashCode
                    @Builder(toBuilder = true)
                    public class CustomerModel {
                        private long customerId;
                        private String customerName;
                        private int customerAge;
                        private String customerMobileNumber;
                        private String customerEmailAddress;
                        private String customerAddress;
                        private LocalDate createdDate;
                    }                    
                  

@Getter: This annotation will help to enable the all getter methods.
@Setter: This annotation will help to enable the all setter methods.
@NoArgsConstructor: This annotation will help to enable the no argument NoArgsConstructor.
@AllArgsConstructor: This annotation will help to create the AllArgsConstructor.
@EqualsAndHashCode: This annotation will overrides the equals and hashcode method.
@Builder: This annotation will eliminates the need to write boilerplate code for constructors with many parameters. It generates the builder class and its methods automatically. this will allow us to set only the fields that is needed, making it easy to work with classes that have many optional attributes.

application.properties

                    spring.application.name=postmappingexample
                    server.port=8083
                  

Postman

Postman call to delete specific customer based on id



                        {
                            "errorCode": 0,
                            "data": "Successfully Removed"
                        }                   
                    

Postman call to delete customer which is not available



                        {
                            "errorCode": 999,
                            "data": "Customer is not available"
                        }                  
                    

Full source code is available in follwong GitHub repository: DeleteMapping example