SpringBoot PutMapping Example

PutMapping example to update or modify the customer. Here, will learn how to use @PutMapping annotation to handle the HTTP PUT requests.

  1. HTTP PUT /api/v1/customer/update – update a customer by specified id.

Will perform the simple customer update operation without using without database storage.

@PutMapping annotation is a simplified compact version of @RequestMapping(method-RequestMathod.PUT)

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.put.mapping.example</groupId>
                        <artifactId>putmappingexample</artifactId>
                        <version>0.0.1-SNAPSHOT</version>
                        <name>putmappingexample</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>

                  

Request Payload

                    {
                        "customerId": 2,
                        "customerName": "sadakhat",
                        "customerAge": 21,
                        "customerMobileNumber": "77022898272",
                        "customerEmailAddress": "sadakhat22.khan@gmail.com",
                        "customerAddress": "Bangalore1"
                    }                                               
                  

PutmappingexampleApplication.java

                    package com.sb.put.mapping.example;

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

                    @SpringBootApplication
                    public class PutmappingexampleApplication {

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

Request.java

                    package com.sb.put.mapping.example.request;

                    import lombok.*;

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

@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.

CustomerController.java

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

                    import com.sb.put.mapping.example.request.CustomerRequest;
                    import com.sb.put.mapping.example.response.APIResponse;
                    import com.sb.put.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;

                        @PutMapping("/update")
                        public ResponseEntity<APIResponse> updateCustomer(@RequestBody CustomerRequest request) {
                            return customerService.updateCustomer(request);
                        }
                    }                    
                  

@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.
@PutMapping: This annotation is used to maps the specified method to the HTTP PUT method for the base URL path.
@RequestBody: This annotation is used to bind the request body to the CustomerRequest object, which represents the CustomerRequest items to be added.
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.put.mapping.example.service;

                    import com.sb.put.mapping.example.request.CustomerRequest;
                    import com.sb.put.mapping.example.response.APIResponse;
                    import org.springframework.http.ResponseEntity;


                    public interface CustomerService {
                        ResponseEntity<APIResponse> updateCustomer(CustomerRequest request);
                    }                   
                  

CustomerModel.java

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

                    import lombok.*;

                    import java.time.LocalDate;

                    @Getter
                    @Setter
                    @NoArgsConstructor
                    @AllArgsConstructor
                    @ToString
                    @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;
                    }                    
                  

CustomerResponse.java

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

                    import lombok.*;

                    import java.time.LocalDate;

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

CustomerServiceImpl.java

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

                    import com.sb.put.mapping.example.model.CustomerModel;
                    import com.sb.put.mapping.example.request.CustomerRequest;
                    import com.sb.put.mapping.example.response.APIResponse;
                    import com.sb.put.mapping.example.response.CustomerResponse;
                    import com.sb.put.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.Optional;
                    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> updateCustomer(CustomerRequest request) {

                            Optional<CustomerModel> customerModelOptional = customers.stream()
                                    .filter(customerModel -> customerModel.getCustomerId() == request.getCustomerId())
                                    .map(customerModel -> {
                                        customerModel.setCustomerName(request.getCustomerName());
                                        customerModel.setCustomerAge(request.getCustomerAge());
                                        customerModel.setCustomerMobileNumber(request.getCustomerMobileNumber());
                                        customerModel.setCustomerEmailAddress(request.getCustomerEmailAddress());
                                        return customerModel;
                                    })
                                    .findFirst();

                            return customerModelOptional.map(customerResponse -> ResponseEntity.ok(
                                    APIResponse.builder()
                                            .errorCode(000)
                                            .data(CustomerResponse.builder()
                                                    .customerId(customerResponse.getCustomerId())
                                                    .customerName(customerResponse.getCustomerName())
                                                    .customerAge(customerResponse.getCustomerAge())
                                                    .customerMobileNumber(customerResponse.getCustomerMobileNumber())
                                                    .customerEmailAddress(customerResponse.getCustomerEmailAddress())
                                                    .customerAddress(customerResponse.getCustomerAddress())
                                                    .createdDate(customerResponse.getCreatedDate())
                                                    .build()
                                            )
                                            .build()
                            )).orElseGet(() -> ResponseEntity.ok(
                                    APIResponse.builder()
                                            .errorCode(999)
                                            .data("Customer is not available")
                                            .build()
                            ));
                        }
                    }
                  

application.properties

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

Postman

Update customer through postman API



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