기존의 댓글 좋아요 기능 코드
// CommentLikeService.java
public ResponseEntity<LikeResponseDto> createLike(Long commentId) {
Comment comment = commentRepository.findById(commentId).orElseThrow(
() -> new IllegalArgumentException("comment가 존재하지 않습니다.")
);
User user = findUser();
checkCommentLike(user, commentId);
comment.createLike(user);
commentRepository.save(comment);
int count = comment.getLikes().size();
comment.setLikeCount(count);
commentRepository.save(comment);
LikeResponseDto responseDto = new LikeResponseDto("좋아요 성공");
return ResponseEntity.ok(responseDto);
}
// Comment.java
@OneToMany(mappedBy = "comment", cascade = CascadeType.ALL, orphanRemoval = true)
private List<CommentLike> likes;
public void createLike(User user){
CommentLike commentLike = new CommentLike(this, user);
this.likes.add(commentLike);
}
수정 코드
// CommentLikeService.java
@Transactional
public LikeResponseDto createLike(Long commentId) {
Comment comment = commentRepository.findById(commentId).orElseThrow(
() -> new IllegalArgumentException("comment가 존재하지 않습니다.")
);
CommentLike commentLike = new CommentLike();
User user = findUser();
checkCommentLike(user, commentId);
commentLike.setComment(comment);
likeRepository.save(commentLike);
comment.increaseLike();
return new LikeResponseDto("좋아요 성공");
}
// Comment.java
public void increaseLike(){
this.likeCount = this.likes.size() + 1;
}
변경된 이유
- Comment 와 CommentLike의 생성시점이 달라 별도로 CommentLike를 저장하는 방식으로 변경
- 댓글 좋아요 조회 기능 또한 Comment에서 like를 받아와서 하기보다는 Comment에 increaseLike메서드 생성으로 likeCount에 1을 더해주고 이를 service에서 불러오는 방향으로 바꾸었다. → 일관된 서비스, 캡슐화
→ 기존 코드에는 @Transactional이 붙어있지 않아 commentRepository.save()와 commentRepository.findById()가 각각의 트랜잭션으로 되어있어, 오류가 났을시 주기가 안맞을 수 있다.
또한, @Transactional이 붙여져 있어야지 더티체킹이 가능하다. 위의 수정된 코드에서 likeRepository.save(commentLike)이후 새로운 업데이트가 발생되었는데, 더티체킹으로 인해 db에까지 반영이 되어 save를 해주지 않아도 된다.
'TIL' 카테고리의 다른 글
240620 : TIL (0) | 2024.06.20 |
---|---|
240618 : TIL (0) | 2024.06.18 |
240611 : TIL - KPT 회고 (0) | 2024.06.11 |
240607: TIL - Token (0) | 2024.06.10 |
240604 TIL (0) | 2024.06.05 |