๐ ๋ฐฑ์๋ ๊ฐ๋ฐ/SPRING
DTO๋ฅผ Request, Response๋ก ๋๋๋ ์ด์
Yeom.log
2025. 2. 15. 04:34
๋ฐ์ํ
DTO(Data Transfer Object)๋ฅผ request์ response๋ก ๋๋๋ ์ด์ ๋ ์ ๋ ฅ๊ณผ ์ถ๋ ฅ์ ์ญํ ์ด ๋ค๋ฅด๊ธฐ ๋๋ฌธ.
๐ ์ฃผ์ : "๋์ ๊ด๋ฆฌ ์์คํ " (Library Management System)
- ์ฌ์ฉ์๊ฐ ์ฑ ์ ์ถ๊ฐํ ๋ Request DTO
- ์ฌ์ฉ์๊ฐ ์ฑ ์ ๋ณด๋ฅผ ์กฐํํ ๋ Response DTO
โ 1. Request DTO (์ ๋ ฅ)
- ํด๋ผ์ด์ธํธ → ์๋ฒ๋ก ๋ฐ์ดํฐ๋ฅผ ๋ณด๋ผ ๋ ์ฌ์ฉ
- ์ฃผ๋ก POST, PUT, PATCH ์์ฒญ์์ ์ฌ์ฉ๋จ
- ์ ํจ์ฑ ๊ฒ์ฌ(ex: @Valid, @NotNull)๋ฅผ ์ ์ฉํ ์ ์์
- ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ํฐํฐ์ 1:1 ๋งคํ๋์ง ์์๋ ๋จ (ํด๋ผ์ด์ธํธ๊ฐ ํ์ํ ๋ฐ์ดํฐ ๊ตฌ์กฐ๋ฅผ ๋ฐ๋ฆ)
package com.example.library.dto.request;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
@Getter
@NoArgsConstructor
public class BookRequestDto {
@NotBlank
private String title;
@NotBlank
private String author;
@Positive
private int price;
public BookRequestDto(String title, String author, int price) {
this.title = title;
this.author = author;
this.price = price;
}
}
โจ ์ฌ์ฉ ์์
@PostMapping("/books")
public ResponseEntity<Void> createBook(@RequestBody @Valid BookRequestDto requestDto) {
bookService.createBook(requestDto);
return ResponseEntity.ok().build();
}
๐ ์ฌ์ฉ์๊ฐ ๋ณด๋ธ ๋ฐ์ดํฐ๋ฅผ ๋ฐ์์ ์ฑ ์ ๋ฑ๋กํ๋ ๋ก์ง
- @NotBlank → title, author๊ฐ ๋น์ด ์์ผ๋ฉด ์ ๋จ
- @Positive → price๋ 0๋ณด๋ค ์ปค์ผ ํจ
โ 2. Response DTO (์ถ๋ ฅ)
- ์๋ฒ → ํด๋ผ์ด์ธํธ๋ก ๋ฐ์ดํฐ๋ฅผ ๋ณด๋ผ ๋ ์ฌ์ฉ
- ์ฃผ๋ก GET ์์ฒญ์์ ์ฌ์ฉ๋จ
- ์ํฐํฐ ๊ทธ๋๋ก ๋ ธ์ถํ์ง ์๋๋ก ๋ณดํธํ๋ ์ญํ
- ๋ถํ์ํ ์ ๋ณด(์: createdAt, updatedAt, DB ID)๋ฅผ ์ ๊ฑฐ ๊ฐ๋ฅ
- ํด๋ผ์ด์ธํธ๊ฐ ํ์๋ก ํ๋ ํ์์ผ๋ก ๊ฐ๊ณต ๊ฐ๋ฅ
package com.example.library.dto.response;
import com.example.library.entity.Book;
import lombok.Getter;
@Getter
public class BookResponseDto {
private Long id;
private String title;
private String author;
private int price;
public BookResponseDto(Book book) {
this.id = book.getId();
this.title = book.getTitle();
this.author = book.getAuthor();
this.price = book.getPrice();
}
}
โจ ์ฌ์ฉ ์์
@GetMapping("/books/{id}")
public ResponseEntity<BookResponseDto> getBookById(@PathVariable Long id) {
BookResponseDto responseDto = bookService.getBookById(id);
return ResponseEntity.ok(responseDto);
}
๐ ์ฑ ์ ๋ณด๋ฅผ ํด๋ผ์ด์ธํธ๊ฐ ๋ณด๊ธฐ ์ข๊ฒ ๊ฐ๊ณตํด์ ์๋ต
- id๋ฅผ ํฌํจํ์ฌ ์ฑ ์ ์ ๋ณด๋ฅผ ์กฐํํ ์ ์์
๐ฅ DTO๋ฅผ ๋๋๋ ์ด์
๊ตฌ๋ถ Request DTO Response DTO
์ญํ | ์ฌ์ฉ์๊ฐ ์ ๋ ฅํ๋ ๋ฐ์ดํฐ | ์ฌ์ฉ์์๊ฒ ๋ณด์ฌ์ค ๋ฐ์ดํฐ |
์ฌ์ฉ ์์ | POST /books | GET /books/{id} |
์ ํจ์ฑ ๊ฒ์ฌ | @Valid ์ฌ์ฉ ๊ฐ๋ฅ | ํ์ ์์ |
๋ณํ ๋ชฉ์ | toEntity() ๋ฉ์๋๋ก ์ํฐํฐ ๋ณํ | ์ํฐํฐ๋ฅผ ์ํ๋ ํํ๋ก ๊ฐ๊ณต |
๋ณด์ | DB ID ๋ ธ์ถ ํ์ ์์ | ๋ถํ์ํ ํ๋ ์จ๊น ๊ฐ๋ฅ |
โ ์ ๋ฆฌ
- Request DTO: ์ฌ์ฉ์๊ฐ ์ ๋ ฅํ๋ ๋ฐ์ดํฐ๋ฅผ ๊ฒ์ฆํ๊ณ ์ํฐํฐ๋ก ๋ณํ
- Response DTO: ์ํฐํฐ ๋ฐ์ดํฐ๋ฅผ ํด๋ผ์ด์ธํธ๊ฐ ๋ณด๊ธฐ ์ข์ ํํ๋ก ๊ฐ๊ณต
๋ฐ์ํ