@PatchMapping Spring Boot Example

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

Before understanding @PatchMapping annotation, let's first understand what is PATCH?

What is PATCH?

Unlike PUT, PATCH applies a partial update to the resource.

This means that you are only required to send the data that you want to update, and it won’t affect or change anything else. For example, if you want to update the first name of the user in the database, you will only be required to send the first name parameter in the HTTP request.

@PatchMapping Overview 

PATCH is used when you want to apply a partial update to the resource and @PatchMapping annotation for mapping HTTP PATCH requests onto specific handler methods.

Specifically, @PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH).
It takes the following optional elements:

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.

@PatchMapping Spring Boot Example 1

PATCH is used when you want to apply a partial update to the resource and @PatchMapping annotation for mapping HTTP PATCH requests onto specific handler methods.

For example, consider we want to update the User resources partially (only emailId field) in a database. So here is the REST API that demonstrates the usage of @PatchMapping annotation:
    @PatchMapping("/users/{id}")
    public ResponseEntity<User> updateUserPartially(
    @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.setUpdatedAt(new Date());
        final User updatedUser = userRepository.save(user);
        return ResponseEntity.ok(updatedUser);
   }

@PatchMapping Spring Boot Example 2

Consider we want to update the Employee resources partially (only firstName field) in a database. So here is the REST API that demonstrates the usage of @PatchMapping annotation:
@PatchMapping("/employees/{id}/{firstName}")
public ResponseEntity<Employee> updateEmployeePartially(@PathVariable Long id, @PathVariable String firstName) {
	try {
		Employee employee = employeeRepository.findById(id).get();
employee.setFirstName(firstName); return new ResponseEntity<Employee>(employeeRepository.save(employee), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } }

Reference

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

Comments