Spring Boot @PatchMapping Example

1. Introduction

1. @PatchMapping is used for mapping HTTP PATCH requests to handler methods.

2. PATCH requests are intended for partial updates to resources, making @PatchMapping ideal for such operations.

3. It is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH).

2. Implementation Steps

1. Create a Spring Boot project with web dependencies.

2. Define a REST controller with a method annotated with @PatchMapping.

3. Configure the method to handle partial updates to a resource.

4. Run the Spring Boot application and use a REST client to send a PATCH request.

3. Implementation Example

Here is the complete code that demonstrates the usage of @PatchMapping annotation:
// Step 2: Define a REST controller to handle PATCH requests
@RestController
public class AccountController {

    // Step 3: Map the handler method to respond to PATCH requests
    @PatchMapping("/accounts/{id}")
    public ResponseEntity<Account> updateAccount(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
        // Step 3: Normally, you would apply the updates to the account
        // Here, we're simulating the update operation for demonstration purposes
        Account account = new Account(); // Simulate account retrieval and update
        updates.forEach((k, v) -> {
            // Apply updates to account based on 'updates' map
        });
        return new ResponseEntity<>(account, HttpStatus.OK);
    }
}

// Define a simple Account class for demonstration purposes
class Account {
    private Long id;
    private String name;
    private double balance;
    // Getters and Setters...
}

// Step 4: Define the main application class
@SpringBootApplication
public class PatchMappingExampleApplication {

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

Output:

{
    "id": 1,
    "name": "Updated Account Name",
    "balance": 1200.00
}

Explanation:

1. @RestController is used to mark the AccountController as a controller suitable for handling REST API calls.

2. @PatchMapping("/accounts/{id}") indicates that the updateAccount method should handle PATCH requests for URLs matching "/accounts/{id}".

3. The method updateAccount takes an id from the URL and a Map<String, Object> representing the fields to update from the request body.

4. In a real application, the service layer would handle the partial update logic. This example assumes the account object is successfully updated.

5. PatchMappingExampleApplication is the main class with a main method that boots up the Spring Boot application.

6. When a PATCH request is made to "/accounts/1" with the appropriate JSON payload, the response is a simulated JSON object representing the updated account, with a 200 OK status code.


Comments