@PutMapping Spring Boot Example

Spring @PutMapping example shows how to use @PutMapping annotation to map HTTP PUT requests onto specific handler methods.

@PutMapping Overview

@PutMapping annotation 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 Example

In this example, the @PutMapping annotation for maps "/employees/{id}" HTTP PUT requests 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);
}

Here is a one more example to update a user PUT request mapping using @PutMapping annotation:
@PutMapping("/users/{id}")
    public ResponseEntity<User> updateUser(
    @PathVariable(value = "id") Long userId,
    @Valid @RequestBody User userDetails) throws ResourceNotFoundException {
         User user = userRepository.findById(userId)
          .orElseThrow(() -> new ResourceNotFoundException("User not found on :: "+ userId));
  
        user.setEmailId(userDetails.getEmailId());
        user.setLastName(userDetails.getLastName());
        user.setFirstName(userDetails.getFirstName());
        user.setUpdatedAt(new Date());
        final User updatedUser = userRepository.save(user);
        return ResponseEntity.ok(updatedUser);
   }

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

Reference


Comments