Spring Framework 에서 HTTP PATCH 요청을 처리하기 위해 사용되는 어노테이션.
주로 리소스의 일부를 수정할 때 사용됨.@RequestMapping(method = RequestMethod.PATCH)
의 축약형으로, 기존 리소스를 부분적으로 업데이트할 때 사용됨
@RestController
@RequestMapping("/api")
public class MyController {
@PatchMapping("/update/{id}")
public ResponseEntity<String> updateResource(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
// id에 해당하는 리소스를 부분적으로 업데이트하는 로직 구현
return ResponseEntity.ok("Resource with ID " + id + " has been updated.");
}
}
@RestController
: 이 클래스가 RESTful 웹 서비스의 컨트롤러임을 나타냄@RequestMapping("/api")
: 클래스 수준의 기본 URL 패턴을 설정함@PatchMapping("/update/{id}")
: /api/update/{id}
로 들어오는 PATCH 요청을 처리함@PathVarialbe
: URL 경로 변수인 id
를 메서드의 매개변수로 바인딩함@RequestBody
: 요청 본문으로 전달된 JSON 데이터를 Map으로 받아옴PATCH 요청은 전체 리소스를 대체하지 않고 일부 속성만 업데이트하는 데 사용됨. 예를 들어, 사용자 정보중 이메일 주소만 업데이트하려는 경우
@RestController
@RequestMapping("/api/users")
public class UserController {
@PatchMapping("/{userId}")
public ResponseEntity<String> updateUserEmail(@PathVariable Long userId, @RequestBody Map<String, Object> updates) {
// userId에 해당하는 사용자의 이메일 주소만 업데이트
if (updates.containsKey("email")) {
String newEmail = updates.get("email").toString();
// 이메일 주소 업데이트 로직
return ResponseEntity.ok("User with ID " + userId + " has been updated with new email: " + newEmail);
}
return ResponseEntity.badRequest().body("Invalid update request");
}
}
@RequestBody Map<String, Object> updates
: 요청 본문으로 전달된 데이터가 부분적으로 업데이트될 필드를 포함하는 Map으로 처리됨containsKey("email")
: Map에 "email" 키가 있는지 확인하고, 해당 값만 업데이트 함일부 속성만 업데이트할 때 DTO(Data Transfer Object) 를 사용할 수도 있음.
@RestController
@RequestMapping("/api/users")
public class UserController {
@PatchMapping("/{userId}")
public ResponseEntity<String> updateUserPartial(@PathVariable Long userId, @RequestBody UserUpdateDTO userUpdateDTO) {
// DTO를 사용해 사용자의 특정 필드를 업데이트하는 로직 구현
return ResponseEntity.ok("User with ID " + userId + " has been partially updated.");
}
}
class UserUpdateDTO {
private String email;
private String phoneNumber;
// getters and setters
}
UserUpdateDTO
는 업데이트할 필드만 포함하는 DTO 클래스@RequestBody UserUpdateDTO userUpdateDTO
를 통해 요청 본문을 DTO로 매핑하여 필드 업데이트를 쉽게 처리할 수 있음.PATCH 요청 후, 업데이트된 리소스의 상태나 일부 변경 사항을 응답으로 반환할 수 있음
@RestController
@RequestMapping("/api/products")
public class ProductController {
@PatchMapping("/{productId}")
public ResponseEntity<Product> updateProductPartial(@PathVariable Long productId, @RequestBody ProductUpdateDTO productUpdateDTO) {
// 제품 정보를 부분적으로 업데이트하는 로직
Product updatedProduct = productService.updateProductPartial(productId, productUpdateDTO);
return ResponseEntity.ok(updatedProduct); // 업데이트된 제품 정보를 반환
}
}
updateProductPartial
메서드는 업데이트된 제품 정보를 반환