본문 바로가기
TIL/내배캠 과제

23.06.29

by J1-H00N 2023. 6. 29.

OneToMany mappedby를 comment로 해서 매핑에 문제가 생긴거였다. comment에서 comment를 조회할 순 없으므로 참조하고 있는 blog를 통해 매핑했어야 했다.

 

삭제는 해결이 됐으나 조회에서 문제가 발생했다.

댓글이 없을 때는 조회가 제대로 작동하나 댓글이 있다면 

InvalidDefinitionException오류가 발생한다.

LAZY로 설정되어 있어서 Jackson으로 Serialize할 때 비어있는 객체를 Serialize하려고 해서 생기는 오류라고 한다.

Hibernate.initialize(blog.getComments());를 추가해 봤으나 같은 에러 발생

// Blog 엔티티
@OneToMany(mappedBy = "blog", cascade = CascadeType.ALL)
@JsonManagedReference
private List<Comment> comments = new ArrayList<>();

// Comment 엔티티
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "blog_id", nullable = false)
@JsonBackReference
private Blog blog;

이 방법도 실패

 

ResponseDto에서 리스트를 따로 만듦으로서 해결

@Getter
public class BlogResponseDto {
    private Long id;
    private String username;
    private String title;
    private String contents;
    private List<CommentResponseDto> commentList;
    private LocalDateTime createdAt;
    private LocalDateTime modifiedAt;

    public BlogResponseDto(Blog blog) {
        this.id = blog.getId();
        this.username = blog.getUsername();
        this.title = blog.getTitle();
        this.contents = blog.getContents();
        this.commentList = new ArrayList<>();
        for (Comment comment : blog.getComments()) {
            CommentResponseDto commentResponseDto = new CommentResponseDto(comment);
            this.commentList.add(commentResponseDto);
        }
        this.createdAt = blog.getCreatedAt();
        this.modifiedAt = blog.getModifiedAt();
    }
}

'TIL > 내배캠 과제' 카테고리의 다른 글

23.07.14  (0) 2023.07.14
23.07.13  (0) 2023.07.13
23.06.28  (0) 2023.06.28
23.06.27  (0) 2023.06.27
23.06.23  (0) 2023.06.26