24/12/30(월)
1. DTO설계
API을 보고, 그에 맞는 Request, Response를 작성해야한다.
//Request
public record CommentRequest(
String content,
String author,
String createdAt,
Long postId
) {
}
//Response
public record CommentResponse(
Long id,
String content,
String author,
String createdAt
) {
}
2. Entity 설계
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//1. 내용은 중복될 수 있음
private String content;
private String author;
private String createdAt;
@ManyToOne
private Post post;
public Comment(String content, String author, String createdAt, Post post) {
this.content = content;
this.author = author;
this.createdAt = createdAt;
this.post = post;
}
public Comment() {
}
public Long getId() {
return id;
}
public String getContent() {
return content;
}
public String getAuthor() {
return author;
}
public String getCreatedAt() {
return createdAt;
}
public Comment(Post post) {
this.post = post;
}
}
id@ManyToOne3. Controller구현
RestController
public class CommentController {
private CommentService commentService;
public CommentController(CommentService commentService) {
this.commentService = commentService;
}
//조회
@GetMapping("/comments")
public List<CommentResponse> read(@RequestParam Long postId){
return commentService.read(postId);
}
@PostMapping("/comments")
public CommentResponse create(@RequestBody CommentRequest commentRequest){
return commentService.save(commentRequest);
}
}
Repository를 사용하려면 댓글 Respository가 있어야한다.
public interface CommentRepository extends JpaRepository<Comment, Long> {
}
service마저 구현
Repository수정
public interface CommentRepository extends JpaRepository<Comment, Long> {
List<Comment> findByPostId(Long postId);
}
이걸 토대로 postId값을 찾아서 output값을 반환해준다.
@Service
public class CommentService {
private CommentRepository commentRepository;
private final PostRepository postRepository;
public CommentService(CommentRepository commentRepository, PostRepository postRepository) {
this.commentRepository = commentRepository;
this.postRepository = postRepository;
}
public List<CommentResponse> read(Long postId) {
//postId를 찾아서 그 아이디에 있는 comment를 찾아라
List<Comment> byPostId = commentRepository.findByPostId(postId);
return byPostId.stream().map(
comment -> new CommentResponse(
comment.getId(),
comment.getContent(),
comment.getAuthor(),
comment.getAuthor())).toList();
}
public CommentResponse save(CommentRequest commentRequest) {
Post post = postRepository.findById(commentRequest.postId()).orElseThrow();
Comment save = commentRepository.save(
new Comment(
commentRequest.content(),
commentRequest.author(),
commentRequest.createdAt(),
post));
return new CommentResponse(save.getId(), save.getContent(), save.getAuthor(), save.getCreatedAt());
}
}
이렇게하면 댓글도 완료!
😐 느낀점
잊지 않아야하는것은 관계를 맺은 id값을 저장할 때, 만들 때, 읽어올 때 등등 사용된다.
언제 어떻게 사용되는지 파악해서 적절하게 사용하는 연습이 필요하다.