🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
🚀 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
nullvalues. - 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!
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment