자바(Java)/스프링부트(SpringBoot)
[SpringBoot] Service단에서의 DTO <--> Entity의 변환.
Jye_647
2023. 7. 11. 20:58
Service는 비즈니스 로직이 있는 곳이다.
DB 저장 또는 조회가 필요할 때 Repository에 요청하는 곳이기도 한데
요청하기 위해서는 DTO에서 Entity로 변환해줘야 한다.
그리고 요청받은 데이터(Entity)를 다시 DTO로 변환해서 컨트롤러(Controller)로 보내줘야 한다.
좀 더 자세한 정보는 https://dahlia15.tistory.com/73
그 과정을 살펴보겠다.
Service
public CommentResponseDto createComment(Long id, CommentRequestDto requestDto, UserDetailsImpl userDetails) {
// dto -> entity
Blog blog = blogRepository.findById(id).orElseThrow(
() -> new NullPointerException("찾을 수 없습니다."));
Comment comment = new Comment(requestDto, userDetails, blog);
// entity -> db저장
commentRepository.save(comment);
// entity -> dto
return new CommentResponseDto(comment);
}
---------------------------------------------------------------------------------
또 다른 Service단 예시이다.
Blog newBlog = new Blog(blogRequestDto);
// entity -> db저장
Blog saveBlog = blogRepository.save(newBlog);
// entity -> ResponseDto 바꿔서 보내줌
BlogResponseDto responseDto = new BlogResponseDto(saveBlog);
return responseDto;
// 한줄로 줄인다면
// return new BlogResponseDto(blogRepository.save(new Blog(blogRequestDto));
ResponseDto
public class BlogResponseDto {
.
.
.
// [게시글 전체 조회를 했을 경우 보여지는 댓글 리스트]
// service에서 controller로 보내기 위해선 entity -> dto로 변환해 줘야한다.
// List로 받아준다. 근데 이 리스트에는 DTO로 받아준다.
private List<CommentResponseDto> commentResponseDto;
public BlogResponseDto(Blog blog) {
// 하지만 받아온 리스트는 Entity인 상태.
this.commentResponseDto = new ArrayList<>();
// 일단, blog엔티티에저장된 댓글entity를 getCommentList로 받아온다.
// Comment를 자료형으로 갖는 comment변수에 하나씩 값을 넣어준다.
for(Comment comment : blog.getCommentList()){
// CommentResponseDto responseDto = new CommentResponseDto(comment)와 같다.
// 즉, dto로 변환해준 entity를 위에 만들어둔 List<CommentResponseDto>에 add.
commentResponseDto.add(new CommentResponseDto(comment));
}
}
}