DTO란
DTO(Data Transfer Object)란 계층간 데이터 교환을 위해 사용하는 객체(Java Beans)이다.
DTO의 사용
DTO를 사용하지 않는 경우
public class User {
private Long id;
private Sting name;
private String email;
private String password;
...
}
@GetMapping("/page/{id}")
public ResponseEntity<User> viewMyPage(@PathVariable("id") Long id) {
return ResponseEntity.ok(userService.viewMyPage(id));
}
이렇게 응답으로 도메인 Model인 User를 넘겨주면 다음와 같은 문제점이 있다.
DTO를 사용하는 경우
public class UserResponseDto {
private String name;
private String email;
}
@GetMapping("/page/{id}")
public ResponseEntity<UserResponseDto> viewMyPage(@PathVariable("id") Long id) {
return ResponseEntity.ok(userService.viewMyPage(id));
}
DTO를 사용하면 앞에서 언급했던 문제들을 해결할 수 있다. 도메인 Model을 캡슐화하고, UI 화면에서 사용하는 데이터만 선택적으로 보낼 수 있다.
DTO의 사용범위
Controller
와 Service
단의 Domain(Entity) 통신
DTO ↔ Domain(Entity) 객체 변환을 Controller
에서 담당
@PostMapping("/article")
public ResponseEntity<ArticleResponseDto> saveArticle(@AuthenticationPrincipal LoginUser loginUser, @RequestBody ArticleRequestDto articleRequestDto) {
Tags tags = tagService.findTagsByTagColor(articleRequestDto.getTagColor());
List<History> history = loginUser.findFormerHistories(tags);
Article article = new Article(articleRequestDto.getId(), articleRequestDto.getName(), articleRequestDto.getContent(), tags, history);
Article savedArticle = articleService.createArticle(article);
return ResponseEntity.ok(ArticleResponseDto.from(savedArticle));
}
public Article createArticle(Article article) {
return articleRepository.save(article);
}
문제점
복잡한 어플리케이션의 경우 여러 Service를 통해 부수적인 정보들을 조회하여 Domain 객체를 구성할 수 있는 경우도 존재하기 때문에 Controller가 View에서 전달받은 DTO만으로 Entity를 구성하기가 어려움.
Controller
와 Service
단의 DTO 통신
DTO ↔ Domain(Entity) 객체 변환을 Service
에서 담당
@PostMapping("/article")
public ResponseEntity<ArticleResponseDto> saveArticle(@AuthenticationPrincipal LoginUser loginUser, @RequestBody ArticleRequestDto articleRequestDto) {
ArticleResponseDto articleResponseDto = articleService.createArticle(loginUser, articleRequestDto);
return ResponseEntity.ok(articleResponseDto);
}
public ArticleResponseDto createArticle(LoginUser loginUser, ArticleRequestDto articleRequestDto) {
Tags tags = tagService.findTagsByTagColor(articleRequestDto.getTagColor());
List<History> history = loginUser.findFormerHistories(tags);
Article article = new Article(articleRequestDto.getId(), articleRequestDto.getName(), articleRequestDto.getContent(), tags, history);
Article savedArticle = articleService.createArticle(createArticle);
return ArticleResponseDto.from(savedArticle);
}
https://tecoble.techcourse.co.kr/post/2021-04-25-dto-layer-scope/ https://velog.io/@minide/Spring-boot-DTO의-사용-범위 https://kafcamus.tistory.com/13 https://kafcamus.tistory.com/12 https://cheolhojung.github.io/posts/record/jpa-entity-vs-dto.html