WEB/SPRING
@PutMapping, @PatchMapping, @GetMapping, @PostMapping ์ ๊ดํ์ฌ...
ITTHING
2025. 2. 15. 04:40
๋ฐ์ํ
๐ ์ฃผ์ : "์จ๋ผ์ธ ์ผํ๋ชฐ (E-commerce)"
- ์ํ์ ์กฐํ (@GetMapping)
- ์๋ก์ด ์ํ์ ์ถ๊ฐ (@PostMapping)
- ์ํ ์ ๋ณด๋ฅผ ์์ (์ ์ฒด ๋ณ๊ฒฝ) (@PutMapping)
- ์ํ ์ ๋ณด๋ฅผ ์์ (๋ถ๋ถ ๋ณ๊ฒฝ) (@PatchMapping)
โ 1. @GetMapping (์กฐํ)
๐ ์ฌ์ฉ์๊ฐ ํน์ ์ํ ์ ๋ณด๋ฅผ ์กฐํํ ๋
@GetMapping("/products/{id}")
public ResponseEntity<ProductResponseDto> getProduct(@PathVariable Long id) {
ProductResponseDto product = productService.getProductById(id);
return ResponseEntity.ok(product);
}
โจ ์ค๋ช
- GET /products/1 ๊ฐ์ ์์ฒญ์ ๋ฐ์ผ๋ฉด
- id๊ฐ 1์ธ ์ํ ์ ๋ณด๋ฅผ ์กฐํํด์ ์๋ต
โ 2. @PostMapping (์๋ก์ด ๋ฐ์ดํฐ ์ถ๊ฐ)
๐ ์ฌ์ฉ์๊ฐ ์ ์ํ์ ๋ฑ๋กํ ๋
@PostMapping("/products")
public ResponseEntity<Void> createProduct(@RequestBody @Valid ProductRequestDto requestDto) {
productService.createProduct(requestDto);
return ResponseEntity.ok().build();
}
โจ ์ค๋ช
- POST /products ์์ฒญ์ ๋ฐ์ผ๋ฉด
- requestDto ๋ฐ์ดํฐ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ์ ์ํ์ DB์ ์ ์ฅ
โ 3. @PutMapping (์ ์ฒด ์์ )
๐ ์ํ ์ ๋ณด๋ฅผ ์ ์ฒด ์์ ํ ๋
@PutMapping("/products/{id}")
public ResponseEntity<Void> updateProduct(
@PathVariable Long id,
@RequestBody @Valid ProductRequestDto requestDto) {
productService.updateProduct(id, requestDto);
return ResponseEntity.ok().build();
}
โจ ์ค๋ช
- PUT /products/1 ์์ฒญ์ ๋ฐ์ผ๋ฉด
- id=1์ธ ์ํ ์ ๋ณด๋ฅผ ์ ๋ถ ์์
- ์์ฒญ ์ ๋ชจ๋ ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํด์ผ ํจ (์ผ๋ถ ๋ฐ์ดํฐ๋ง ์ ๋ฌํ๋ฉด ๊ธฐ์กด ๊ฐ์ด ์ฌ๋ผ์ง ์ ์์)
โ 4. @PatchMapping (๋ถ๋ถ ์์ )
๐ ์ํ ์ ๋ณด๋ฅผ ์ผ๋ถ๋ง ์์ ํ ๋
@PatchMapping("/products/{id}")
public ResponseEntity<Void> updateProductPrice(
@PathVariable Long id,
@RequestBody Map<String, Object> updates) {
productService.updateProductPartially(id, updates);
return ResponseEntity.ok().build();
}
โจ ์ค๋ช
- PATCH /products/1 ์์ฒญ์ ๋ฐ์ผ๋ฉด
- ํน์ ํ๋ (price, stock ๋ฑ) ๋ถ๋ถ์ ์ผ๋ก ์์ ๊ฐ๋ฅ
- ์๋ฅผ ๋ค์ด { "price": 20000 }๋ง ๋ณด๋ด๋ฉด ๊ฐ๊ฒฉ๋ง ์์ ๋จ
โ ์ ๋ฆฌ
์ด๋ ธํ ์ด์ HTTP ๋ฉ์๋ ์ฌ์ฉ ๋ชฉ์ ํน์ง
@GetMapping | GET | ๋ฐ์ดํฐ ์กฐํ | URL์ ํ๋ผ๋ฏธํฐ ํฌํจ (/products/1) |
@PostMapping | POST | ์๋ก์ด ๋ฐ์ดํฐ ์ถ๊ฐ | ์์ฒญ ๋ณธ๋ฌธ (RequestBody)์ ํ์ฉ |
@PutMapping | PUT | ๋ฐ์ดํฐ ์ ์ฒด ์์ | ๋ชจ๋ ํ๋๋ฅผ ํฌํจํ์ฌ ์์ฒญํด์ผ ํจ |
@PatchMapping | PATCH | ๋ฐ์ดํฐ ์ผ๋ถ ์์ | ๋ณ๊ฒฝํ ํ๋๋ง ์์ฒญ ๊ฐ๋ฅ |
๋ฐ์ํ