@PutMapping Spring Boot Example

Spring @PutMapping example shows how to use @PutMapping annotation to map HTTP PUT requests onto specific handler methods.
Check out free Spring boot projects at Free Spring Boot Projects 

Before understanding @PutMapping annotation, let's first understand what is PUT HTTP method? 

What is PUT?

PUT HTTP method is used to modify/update a resource where the client sends data that updates the entire resource.

It is used to set an entity’s information completely. PUT is similar to POST in that it can create resources, but it does so when there is a defined URI. PUT overwrites the entire entity if it already exists, and creates a new resource if it doesn’t exist.

@PutMapping Annotation Overview

As we know PUT HTTP method is used to update/modify the resource so @PutMapping annotation is used for mapping HTTP PUT requests onto specific handler methods.
Specifically, @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT).
@PutMapping annotation has below optional attributes:
consumes – Narrows the primary mapping by media types that can be consumed by the mapped handler.
headers  – The headers of the mapped request, narrowing the primary mapping.
name – Assign a name to this mapping.
params – The parameters of the mapped request, narrowing the primary mapping.
path – The primary mapping expressed by this annotation.
produces – Narrows the primary mapping by media types that can be produced by the mapped handler.
value – The primary mapping expressed by this annotation.

@PutMapping Example 1

Let's dive into an example where we develop a simple user management system with the ability to update user details. 

Project Setup 

Begin by initiating a new Spring Boot project using the Spring Initializer or your preferred development environment. 

The Model 

For our user management system, let's work with a User entity.

public class User {
    private Long id;
    private String name;
    private String email;

    // Constructors, getters, setters, and other methods.
}

The Controller 

Next, we'll design a UserController that will handle our HTTP PUT requests.
@RestController
@RequestMapping("/api/users")
public class UserController {

    private Map<Long, User> users = new HashMap<>();

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        if (users.containsKey(id)) {
            User existingUser = users.get(id);
            existingUser.setName(userDetails.getName());
            existingUser.setEmail(userDetails.getEmail());
            users.put(id, existingUser);
            return new ResponseEntity<>(existingUser, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}
Key points to understand: 
@PutMapping("/{id}") updates the user whose ID matches the provided path variable. 

The @RequestBody annotation tells Spring Boot to populate the userDetails object with data from the request body.

 The method returns a ResponseEntity which is a more flexible way of returning both the data and the HTTP status code.

@PutMapping Example 2

Consider we want to update the existing Employee resource so the below example demonstrates the usage of @PutMapping annotation, which is used to map "/employees/{id}" HTTP PUT request onto a specific handler method - updateEmployee():
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long employeeId,
  @Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
     Employee employee = employeeRepository.findById(employeeId)
     .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));

     employee.setEmailId(employeeDetails.getEmailId());
     employee.setLastName(employeeDetails.getLastName());
     employee.setFirstName(employeeDetails.getFirstName());
     final Employee updatedEmployee = employeeRepository.save(employee);
     return ResponseEntity.ok(updatedEmployee);
}

Check out a complete example at Spring Boot 2 Hibernate 5 MySQL CRUD REST API Tutorial

Reference

Spring Boot Annotations.
Spring Boot CRUD REST APIs with MySQL Database

Comments