🌿SPRING/🌱연습[SPRING]

[SPRING] 입문주차 과제 - 전체 게시글 목록 조회 / 게시글 조회

디카페인라떼 2022. 8. 17. 23:45

03 주차 과제를 잘해낸 줄 알았더니 아니었다 ... 

전체 게시글 조회 시 : 제목/ 작성자명/ 작성 날짜 가 떠야하고

게시글 조회 시 : 제목/ 작성자명/ 작성날짜 / 작성내용 이 떠야했다..

 

어제까지 만든건 모두 다 떴다 ...^^ 작성날짜/수정날짜/id/제목/내용/작성자/내용/비밀번호 모두 .. 

배포까지 다하고나서야 알게되어서 ... ㅎㅎ 그치만 제출 전까지 시간이 남은 상태에서라도 알게되었으니까 수정해야지..ㅎ

 


<전체 게시글 조회시>

 

[Controller]

    @GetMapping("/api/post")
    public List<Posting> getPosting() {
        return postingRepository.findAllByOrderByModifiedAtDesc();
    }

Entity가 리스트 형태로 나온다

 

그렇다면 일단 Entity로 가서

@JsonIgnore을 추가해서 조회시 안뜨도록 처리했다.(id/내용/비밀번호)

@Getter
@NoArgsConstructor
@Entity
public class Posting extends Timestamped{

    
    @JsonIgnore
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private Long id;

    @Column(nullable = false)
    private String title;

    @JsonIgnore
    @Column(nullable = false)
    private String content;

    @Column(nullable = false)
    private String author;

    @JsonIgnore
    @Column(nullable = false)
    private String password;

그러고 나니 <게시글 조회> 시에도 세가지 항목밖에 안보였다...

(제목/ 작성자명/ 작성날짜 / 작성내용) 모두 떠야 하는데 ^^.. 멘붕...

 

참고 블로그 

 

게시글 조회 [Controller]

    //게시글 조회
    @GetMapping("/api/post/{id}")
    public Posting getPosting(@PathVariable Long id) {
        return  postingRepository.findById(id).orElseThrow(
                () -> new NullPointerException("해당 아이디가 존재하지 않습니다.")
        );
    }

전체 게시글 조회와 같이 내용들이 뜨게 되어있고 repository를 통해 findById로 매개변수로 id값을 받도록 만 되어있다.. 그러니 Entity에서 @JsonIgnore를 쓰니까 똑같이 안뜨는 것... 

 

게시글 조회시 뜨는 내용을 다르게 하려면 Dto를 따로 설정해 준 뒤 서비스를 다시 만들어 주면 된다.

 

[PostingResponseDto]->응답으로 보내주는 Dto이므로 

@Getter
public class PostingResponseDto {
    private final String title;
    private final String content;
    private final String author;

}

 

그리고나서 [Service]에서 findById를 만들어준다 . (repository에서 기능을 끌어서 쓸수없기때문!)

    @Transactional
    public PostingResponseDto findById (Long id) {
        Posting entity = postingRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다 id =" +id));
        return new PostingResponseDto(entity);
    }

이러니까 Posting entity에서 오류가 떴다... entity로 받아주는 게 없기때문... 다시 responseDto수정

 

@Getter
public class PostingResponseDto extends Timestamped{
    private final String title;
    private final String content;
    private final String author;


    @Builder
    public PostingResponseDto (Posting entity) {
        this.title = entity.getTitle();
        this.content = entity.getContent();
        this.author = entity.getAuthor();
    }
}

이대로 실행하니 (제목/ 작성자명 / 작성내용)은 뜨는데 이제 작성날짜가 뜨지 않는다....

responseDto가 게시글 조회시 출력되는 거니까 Dto만 수정해주면된다.

 

그전에 Timestamped class에서 private -> protected로 변경해준다

@Getter // get 함수를 자동 생성합니다.
@MappedSuperclass // 멤버 변수가 컬럼이 되도록 합니다.
@EntityListeners(AuditingEntityListener.class) // 변경되었을 때 자동으로 기록합니다.
public abstract class Timestamped {

    @CreatedDate // 최초 생성 시점
    protected LocalDateTime createdAt;

    @JsonIgnore
    @LastModifiedDate // 마지막 변경 시점
    protected LocalDateTime modifiedAt;


}

 

❓ Private은 자기자신 클래스에서만 사용가능하므로 상속받아 사용하려면 Protected로 수정해주어야함! 

참고 : 2022.08.10 - [JAVA] - [JAVA] 접근 제한자

 

그리고나서 [ResponseDto]수정

@Getter
@MappedSuperclass //②어노테이션은 상속되지 않으므로 복붙
@EntityListeners(AuditingEntityListener.class) //②어노테이션은 상속되지 않으므로 복붙
public class PostingResponseDto extends Timestamped{  //①상속
    private final String title;
    private final String content;
    private final String author;


    @Builder
    public PostingResponseDto (Posting entity) {
        this.title = entity.getTitle();
        this.content = entity.getContent();
        this.author = entity.getAuthor();
        super.createdAt = entity.getCreatedAt(); //부모 클래스를 끌어와 쓰는 걸로 생성자에 추가

    }
}

 

이제야 출력이 제대로 나온다