[Spring] Inner class로 DTO 관리하기

김재연·2023년 3월 12일
2

수숙관

목록 보기
8/17
post-thumbnail

🤔 고민

큰 덩어리는 비슷한데 조금씩만 다른 DTO들을 호출할때마다 목적에 맞게 하나씩 만들어야하는지, 아니면 하나로 뭉쳐서 필요한것만 가져다쓰면 되는지..

매번 만들자니 파일만 쓸데없이 늘어남 + 이름 붙이기도 힘들고, 하나로 뭉치자니 입출력이 명확히 안보임 + 필요없는 필드들도 왔다갔다하는게 마음에 안들어서 고민을 하다가

💡 DTO inner class

DTO를 inner class로 만들면 깔끔하대서 해봤다. 나름 괜찮은 방법인듯!

/* ReviewDTO */
public class ReviewDTO {

    @Getter
    @Setter
    /* Review Create할 때 쓸 DTO => ReviewDTO.Create */
    public static class Create {
        private Long tutoringId;
        private String body;
        private Long tagId;
    }

    @Getter
    @Setter
    /* Review Update할 때 쓸 DTO => ReviewDTO.Update */
    public static class Update {
        private String body;
        private Long tagId;
    }

    @Getter
    @Setter
    /* Review Check할 때 쓸 DTO => ReviewDTO.Check */
    public static class Check {
        private Boolean isCompleted;
    }

    @Getter
    @Setter
    /* Review 반환할 때 쓸 DTO => ReviewDTO.Response */
    public static class Response {
        private Long id;
        private String body;
        private Boolean isCompleted;
        private ReviewNoteDTO note;
        private ReviewTagDTO tag;

        /* Entity -> DTO Response */
        public Response(Review review) {
            this.id = review.getId();
            this.body = review.getBody();
            this.isCompleted = review.getIsCompleted();
            this.note = new ReviewNoteDTO(review.getNote());
            this.tag = new ReviewTagDTO(review.getTag());
        }

        /* Entity List -> DTO Response List */
        public static List<Response> ResponseList (List<Review> reviewList) {
            List<Response> responseList = reviewList.stream()
            										.map(o->new Response(o))
            										.collect(Collectors.toList());
            return responseList;
        }

        @Getter
        public static class ReviewNoteDTO {
            private Long id;

            public ReviewNoteDTO(Note note) {
                this.id = note.getId();
            }
        }

        @Getter
        public static class ReviewTagDTO {
            private Long id;
            private String name;

            public ReviewTagDTO(Tag tag) {
                this.id = tag.getId();
                this.name = tag.getName();
            }
        }
    }
}
/* service 예시 */
public String createReview(ReviewDTO.Create createReview) {
	Optional<Tutoring> tutoring = tutoringRepository.findById(createReview.getTutoringId());
	Optional<Tag> tag = tagRepository.findById(createReview.getTagId());
	// ...생략...
}

public List<ReviewDTO.Response> reviewList() {
	List<Review> reviewList = reviewRepository.findAll();
	return ReviewDTO.Response.ResponseList(reviewList);
}

이렇게 하면 목적마다 조금씩 다른 DTO들을 각각 만들어서 파일 1개에 때려넣을 수 있다!👍 이름도 깔쌈하게 붙어서 맘에 듦


Reference

DTO에 관한 생각
Spring Boot에서 깔끔하게 DTO 관리하기
인프런 질의응답 - dto (김영한님 답변)

profile
일기장같은 공부기록📝

3개의 댓글

comment-user-thumbnail
2024년 6월 26일

와우

답글 달기
comment-user-thumbnail
2025년 1월 9일

정말 정말 감사합니다

답글 달기
comment-user-thumbnail
2025년 8월 31일

https://kumu.io/bothbest
https://kumu.io/bothbest/why-do-people-consider-bamboo-flooring
https://www.aleviforum.com/bothbest
https://worldschoolface.com/index.php/profile-55061
https://amazemediacollege.com/forums/users/bothbest/
https://forum.kiasuparents.com/user/bothbest
https://zeroone.art/profile/bothbest
https://www.photocontest.gr/users/bamboo-flooring/
https://medibulletin.com/author/bothbest/
https://www.classiccitynews.com/profile/bothbest/profile
https://www.happycampersmontessori.com/profile/bothbest/profile
https://www.levelupbasketballtrainingllc.com/profile/bothbest/profile
https://www.housedumonde.com/profile/bothbest/profile
https://www.printables.com/@bothbest_3582539
https://www.do3d.com/profile/bothbest/profile
https://www.cambodgemag.com/en/profile/bothbest/profile
https://www.yapstate.gov.fm/profile/bothbest/profile
https://www.mimigstyle.com/profile/bothbest/profile
https://www.clevercomponents.com/portal/community/p9957/bamboo-flooring.aspx
https://www.salesfully.com/profile/bothbest/profile
https://www.blog.bhsusa.com/profile/chinahousehold65215/profile
https://www.informe21.com/profile/bothbest/profile
https://www.hentai-foundry.com/user/bothbest/blogs/20357/The-Unique-Journey-of-Bamboo-Flooring
https://infiniteabundance.mn.co/members/35641220
https://infiniteabundance.mn.co/posts/90004462
https://infiniteabundance.mn.co/posts/90004531
https://visiontrainstation.mn.co/members/35641262
https://visiontrainstation.mn.co/posts/90004581
https://visiontrainstation.mn.co/posts/mind-blowing-unheard-facts-about-bamboo-floors
https://womenindata.mn.co/members/35641326
https://pathwaycitychurch.mn.co/members/35641360
https://pathwaycitychurch.mn.co/posts/90004764
https://pathwaycitychurch.mn.co/posts/90004776
https://aisalon.mn.co/members/35641436
https://www.palistrong.org/members/35641496
https://authortunities-hub.mn.co/members/35641539
https://authortunities-hub.mn.co/posts/eco-friendly-flooring-why-bamboo-is-a-sustainable-choice
https://authortunities-hub.mn.co/posts/bamboo-flooring-thailand-supplier

답글 달기