항해99/스프링 숙련

게시판 댓글 작성 및 조회(수정필요)

숲별 2022. 10. 13. 03:10
728x90

-----CommentController

@RequiredArgsConstructor
@RestController
public class CommentController {
    private final CommentRepository commentRepository;
    private final CommentService commentService;
    private final PostRepository postRepository;

    @PostMapping("/api/auth/comment")
    public Comment createComment(@RequestBody CommentRequestDto commentRequestDto){
        Post post = postRepository.findById(commentRequestDto.getPostid()).orElseThrow(
                () -> new IllegalArgumentException("아이디가 존재하지 않습니다."));
        Comment comment = new Comment(commentRequestDto, post);
        return commentRepository.save(comment);
    }
}

 

----Comment.java

@ManyToOne
@JoinColumn(name = "post_id")
private Post post;


public Comment(CommentRequestDto commentRequestDto, Post post) {
    this.comment = commentRequestDto.getComment();
    this.username = commentRequestDto.getUsername();
    this.post = post;

}

 

----Post.java.....위아래 바뀌어서 들어가야 하나...?


@JsonIgnore
@OneToMany(mappedBy = "post", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
private List<Comment> comments = new ArrayList<>();

 

@JoinColumn은 ..

 

cascadeType.REMOVE는 게시글 삭제시 댓글 같이 삭제되기 위함.

 

https://dev-coco.tistory.com/132

 

Spring Boot JPA 게시판 댓글 작성 및 조회 구현하기

게시판에서 댓글은 없어선 안될 중요한 부분이라고 생각한다. 그래서 오늘은 게시판의 댓글 기능을 구현해보려 한다. 1. Entity 1-1. Comment @Builder @AllArgsConstructor @NoArgsConstructor @Getter @Table(n..

dev-coco.tistory.com