1.Entity
package com.spring.loginprac.model;
import com.spring.loginprac.dto.NoticeDto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.Date;
@Getter
@Setter
@NoArgsConstructor
@Entity
public class Comment {
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long id;
// nullable: null 허용 여부
// unique: 중복 허용 여부 (false 일때 중복 허용)
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String comment;
@Column(nullable = false)
private Date date;
@ManyToOne
@JoinColumn(name = "post_id")
private Notice notice;
}
2.Controller
//댓글 보기
@GetMapping("/notice/detail/comment/{id}")
public List<Comment> commentView(@PathVariable Long id){
return noticeService.commentView(id);
}
3.Service
public List<Comment> commentView(Long id) {
Notice notice = noticeRepository.findById(id).get();
return commentRepository.findCommentsByNotice(notice);
}
JPA 연관관계 맵핑을 통해서
Notice와 Comment 사이의 다대일 연관관계를 지었다.
하나의 게시글에는 여러개의 댓글이 달릴 수 있기 때문,
연관관계 맵핑이 완료되면 디버깅했을때 자연스럽게 테이블이 형성된다.
이후 Service에선 notice 엔티티를 개체화 한 후 commentRepository에서 검색했다.
결과