제목, 작성자명(nickname), 작성 날짜를 조회하기
PostResponseDto에는 여러가지 필드들이 있지만 위의 3가지만 출력을 해보기로 하였다
PostResponseDto
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class PostResponseDto {
    private Long id;
    private String nickName;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime createdAt;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime modifiedAt;
    private String title;
    private String content;
    private List<CommentResponseDto> comments;
    public PostResponseDto(Post post) {
        this.id = post.getId();
        this.title = post.getTitle();
        this.content = post.getContent();
        this.nickName = post.getUser().getNickname();
        this.createdAt = post.getCreatedAt();
        this.modifiedAt = post.getModifiedAt();
        this.comments = post.getComments()
                .stream()
                .map(CommentResponseDto::new)
                .collect(Collectors.toList());
    }
    public PostResponseDto(String nickName, LocalDateTime createdAt,String title) {
        this.nickName = nickName;
        this.createdAt = createdAt;
        this.title = title;
    }
}
일단 PostResponseDto를 만들어주고 제목, 작성자명, 작성날짜를 매개변수로 하는 생성자를 만들어줌
포스트맨을 이용해서 결과 확인

원하는 작성자, 작성일, 제목을 불러왔지만 나머지 필드들도 null값으로 같이 나오면서
지저분한 결과가 출력된 것을 볼 수 있음
@JsonInclude(JsonInclude.Include.NON_NULL)
@Getter
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL) // 추가
public class PostResponseDto {
    private Long id;
    private String nickName;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime createdAt;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime modifiedAt;
    private String title;
    private String content;
    private List<CommentResponseDto> comments;
    public PostResponseDto(Post post) {
        this.id = post.getId();
        this.title = post.getTitle();
        this.content = post.getContent();
        this.nickName = post.getUser().getNickname();
        this.createdAt = post.getCreatedAt();
        this.modifiedAt = post.getModifiedAt();
        this.comments = post.getComments()
                .stream()
                .map(CommentResponseDto::new)
                .collect(Collectors.toList());
    }
    public PostResponseDto(String nickName, LocalDateTime createdAt,String title) {
        this.nickName = nickName;
        this.createdAt = createdAt;
        this.title = title;
    }
}
@JsonInclude(JsonInclude.Include.NON_NULL)을 PostResponseDto에 추가해줌

null값로 이루어진 필드들이 전부 사라지고 내가 원하는 필드들만 출력이 되는 것을 볼 수 있음
'TIL' 카테고리의 다른 글
| 다대다 관계에서 중간테이블 만들기 / 순환참조 해결 (0) | 2024.01.03 | 
|---|---|
| Could not autowire. No beans of 오류 / 프로그래머스<기사단원의 무기> (0) | 2023.12.13 | 
| 프로그래머스 덧칠하기, 소수만들기 (0) | 2023.12.12 | 
| [JPA] 값 타입 컬렉션 (0) | 2023.12.06 | 
| JUnit Assert(단정) 메서드 (2) | 2023.12.04 | 
 
			
			
댓글