개념
| PUT | PATCH | |
| 의미 | 전체 수정 | 부분 수정 |
| 리소스 변경 방식 | 기존 데이터를 완전히 덮어씀 | 일부 필드만 수정 가능 |
| 보내는 데이터 형태 | 전체 객체를 포함 | 변경할 필드만 보냄 |
| RESTful 원칙 | 멱등성(같은 요청을 여러 번 보내도 결과 동일) | 보장 X (서버 구현 방식에 따라 다름) |
예시
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private String email;
private String address;
}
PUT 사용/요청 예시
@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User newUser) {
User existingUser = userService.findById(id);
existingUser.setName(newUser.getName());
existingUser.setEmail(newUser.getEmail());
existingUser.setAddress(newUser.getAddress());
userService.save(existingUser);
return ResponseEntity.ok(existingUser);
}
PUT /users/1
{
"name": "John",
"email": "john@naver.com",
"address": "Seoul"
}
- 모든 필드를 포함
- 누락된 필드는 null 처리될 수 있음.
PATCH 사용/요청 예시
@PatchMapping("/users/{id}")
public ResponseEntity<User> patchUser(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
User existingUser = userService.findById(id);
updates.forEach((key, value) -> {
Field field = ReflectionUtils.findField(User.class, key);
if (field != null) {
field.setAccessible(true);
ReflectionUtils.setField(field, existingUser, value);
}
});
userService.save(existingUser);
return ResponseEntity.ok(existingUser);
}
PATCH /users/1
{
"email": "new@naver.com"
}
email 필드만 변경, 다른 필드는 유지.
필요한 데이터만 보내면 됨.
'Spring Boot' 카테고리의 다른 글
| Spring 예외 처리 GlobalExceptionHandler 사용 이유 (0) | 2025.02.27 |
|---|---|
| RequestDto, ResponseDto 사용하는 이유 (0) | 2025.02.20 |
| private final vs autowired 차이점 (0) | 2025.02.14 |
| RequestParam vs PathValue 차이 (0) | 2025.02.13 |
| [Spring Boot] HTTP 상태 코드 (HTTP Status Code) (2) | 2024.12.19 |