@PutMapping vs @PatchMapping in Spring Boot

🚀 Introduction: Understanding @PatchMapping vs @PutMapping

In Spring Boot REST APIs, both @PutMapping and @PatchMapping are used to update existing resources, but they serve different purposes.

Key Differences:

Feature @PutMapping @PatchMapping
Purpose Updates entire resource (full update). Updates only specific fields (partial update).
HTTP Method Uses PUT Uses PATCH
Request Body Requires the complete object. Requires only the fields to be updated.
Data Overwrite Overwrites all fields (missing fields may be set to null). Updates only provided fields, keeping others unchanged.
Use Case When updating all properties of a resource. When updating only selected properties of a resource.

1️⃣ Understanding @PutMapping in Spring Boot

📌 Use @PutMapping when updating an entire resource.
✔ Requires complete object in the request body.
✔ Missing fields in the request may be reset to default or null.

Example: Using @PutMapping for Full Update

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        return ResponseEntity.ok(userService.updateUser(id, user));
    }
}

📌 Request (Full Update with PUT)

{
  "id": 1,
  "name": "Ramesh",
  "email": "ramesh@example.com",
  "age": 30
}

The entire object is updated.

📌 If a field is missing in the request, it might be set to null.

2️⃣ Understanding @PatchMapping in Spring Boot

📌 Use @PatchMapping when updating only specific fields.
✔ Requires only the fields to be updated.
✔ Keeps other fields unchanged.

Example: Using @PatchMapping for Partial Update

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PatchMapping("/{id}")
    public ResponseEntity<User> partiallyUpdateUser(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
        return ResponseEntity.ok(userService.partialUpdateUser(id, updates));
    }
}

📌 Request (Partial Update with PATCH)

{
  "email": "ramesh.new@example.com"
}

Only the email field is updated, other fields remain unchanged.

3️⃣ Key Differences Between @PutMapping and @PatchMapping

Feature @PutMapping @PatchMapping
HTTP Method PUT PATCH
Update Type Full update (Replaces entire object). Partial update (Updates only specified fields).
Request Body Requires the complete resource. Requires only the fields to be updated.
Data Loss Risk Yes (If a field is missing, it may be set to null). No (Only modifies provided fields, keeping others intact).
Common Use Case Updating all fields of a resource. Updating only some fields of a resource.

📌 Best Practice:
✔ Use PUT (@PutMapping) when updating all fields of an entity.
✔ Use PATCH (@PatchMapping) when updating only specific fields.

4️⃣ Handling Partial Updates with @PatchMapping

📌 Using Map<String, Object> for Dynamic Updates

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User partialUpdateUser(Long id, Map<String, Object> updates) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new UserNotFoundException("User not found"));

        updates.forEach((key, value) -> {
            Field field = ReflectionUtils.findField(User.class, key);
            if (field != null) {
                field.setAccessible(true);
                ReflectionUtils.setField(field, user, value);
            }
        });

        return userRepository.save(user);
    }
}

📌 How It Works:
✅ Uses ReflectionUtils to dynamically update only the provided fields.
✅ Avoids setting missing fields to null.

5️⃣ When to Use @PutMapping vs @PatchMapping?

Use Case Use @PutMapping Use @PatchMapping
Updating all fields ✅ Yes ❌ No
Updating only some fields ❌ No ✅ Yes
Resetting missing fields to default values ✅ Yes ❌ No
Avoiding null overwrites ❌ No ✅ Yes
Bulk updates (e.g., admin updating user profiles) ✅ Yes ❌ No
User updating only a few fields (e.g., changing email) ❌ No ✅ Yes

📌 Best Practice:
✔ Use @PutMapping when sending a complete object update.
✔ Use @PatchMapping when sending a partial update.

6️⃣ REST API Best Practices for PUT and PATCH

When to Use PUT (@PutMapping)

  • When updating all fields of an entity.
  • When missing fields should be reset to default values.
  • When ensuring consistent data structures.

📌 Example Use Case: Updating User Profile

{
  "id": 1,
  "name": "Ramesh",
  "email": "ramesh@example.com",
  "age": 30
}

All fields are updated, missing fields may be reset.

When to Use PATCH (@PatchMapping)

  • When updating only a few fields of an entity.
  • When avoiding overwriting other fields with null values.
  • When using dynamic updates where fields vary per request.

📌 Example Use Case: Changing Only Email

{
  "email": "ramesh.new@example.com"
}

Only email is updated, other fields remain unchanged.

🎯 Summary: Best Practices for @PatchMapping and @PutMapping

Use @PutMapping when updating an entire resource.
Use @PatchMapping when updating only specific fields.
Use Map<String, Object> and ReflectionUtils for dynamic partial updates.
Ensure PUT requests always contain the full object to prevent data loss.
Ensure PATCH requests only modify provided fields.

🚀 Following these best practices ensures clean, maintainable Spring Boot APIs!

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare