Skip to content

Commit 1b74e7c

Browse files
committed
Ref: 엔티티 개선
1 parent d8af8a8 commit 1b74e7c

25 files changed

+385
-237
lines changed

src/main/java/com/back/domain/board/comment/entity/Comment.java

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,63 +9,80 @@
99

1010
import java.util.ArrayList;
1111
import java.util.List;
12+
import java.util.Objects;
1213

1314
@Entity
1415
@Getter
1516
@NoArgsConstructor
1617
public class Comment extends BaseEntity {
1718
@ManyToOne(fetch = FetchType.LAZY)
18-
@JoinColumn(name = "post_id")
19+
@JoinColumn(name = "post_id", nullable = false)
1920
private Post post;
2021

2122
@ManyToOne(fetch = FetchType.LAZY)
22-
@JoinColumn(name = "user_id")
23+
@JoinColumn(name = "user_id", nullable = false)
2324
private User user;
2425

26+
@Column(nullable = false, columnDefinition = "TEXT")
2527
private String content;
2628

27-
// TODO: 추후 CommentRepositoryImpl#getCommentsByPostId 로직 개선 필요, ERD에도 반영할 것
2829
@Column(nullable = false)
2930
private Long likeCount = 0L;
3031

31-
// 해당 댓글의 부모 댓글
3232
@ManyToOne(fetch = FetchType.LAZY)
3333
@JoinColumn(name = "parent_comment_id")
3434
private Comment parent;
3535

36-
// 해당 댓글에 달린 대댓글 목록
3736
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
3837
private List<Comment> children = new ArrayList<>();
3938

4039
@OneToMany(mappedBy = "comment", cascade = CascadeType.ALL, orphanRemoval = true)
4140
private List<CommentLike> commentLikes = new ArrayList<>();
4241

4342
// -------------------- 생성자 --------------------
44-
public Comment(Post post, User user, String content) {
45-
this.post = post;
46-
this.user = user;
47-
this.content = content;
48-
}
49-
5043
public Comment(Post post, User user, String content, Comment parent) {
5144
this.post = post;
5245
this.user = user;
5346
this.content = content;
5447
this.parent = parent;
48+
post.addComment(this);
49+
user.addComment(this);
50+
}
51+
52+
// -------------------- 정적 팩토리 메서드 --------------------
53+
/** 루트 댓글 생성 */
54+
public static Comment createRoot(Post post, User user, String content) {
55+
return new Comment(post, user, content, null);
56+
}
57+
58+
/** 대댓글 생성 */
59+
public static Comment createChild(Post post, User user, String content, Comment parent) {
60+
Comment comment = new Comment(post, user, content, parent);
61+
parent.getChildren().add(comment);
62+
return comment;
63+
}
64+
65+
// -------------------- 연관관계 편의 메서드 --------------------
66+
public void addLike(CommentLike like) {
67+
this.commentLikes.add(like);
68+
}
69+
70+
public void removeLike(CommentLike like) {
71+
this.commentLikes.remove(like);
5572
}
5673

5774
// -------------------- 비즈니스 메서드 --------------------
58-
// 댓글 업데이트
75+
/** 댓글 내용 수정 */
5976
public void update(String content) {
6077
this.content = content;
6178
}
6279

63-
// 좋아요 수 증가
80+
/** 좋아요 수 증가 */
6481
public void increaseLikeCount() {
6582
this.likeCount++;
6683
}
6784

68-
// 좋아요 수 감소
85+
/** 좋아요 수 감소 */
6986
public void decreaseLikeCount() {
7087
if (this.likeCount > 0) {
7188
this.likeCount--;

src/main/java/com/back/domain/board/comment/entity/CommentLike.java

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,31 @@
22

33
import com.back.domain.user.entity.User;
44
import com.back.global.entity.BaseEntity;
5-
import jakarta.persistence.Entity;
6-
import jakarta.persistence.FetchType;
7-
import jakarta.persistence.JoinColumn;
8-
import jakarta.persistence.ManyToOne;
5+
import jakarta.persistence.*;
96
import lombok.AllArgsConstructor;
107
import lombok.Getter;
118
import lombok.NoArgsConstructor;
129

1310
@Entity
1411
@Getter
1512
@NoArgsConstructor
16-
@AllArgsConstructor
13+
@Table(
14+
uniqueConstraints = @UniqueConstraint(columnNames = {"comment_id", "user_id"})
15+
)
1716
public class CommentLike extends BaseEntity {
1817
@ManyToOne(fetch = FetchType.LAZY)
19-
@JoinColumn(name = "comment_id")
18+
@JoinColumn(name = "comment_id", nullable = false)
2019
private Comment comment;
2120

2221
@ManyToOne(fetch = FetchType.LAZY)
23-
@JoinColumn(name = "user_id")
22+
@JoinColumn(name = "user_id", nullable = false)
2423
private User user;
24+
25+
// -------------------- 생성자 --------------------
26+
public CommentLike(Comment comment, User user) {
27+
this.comment = comment;
28+
this.user = user;
29+
comment.addLike(this);
30+
user.addCommentLike(this);
31+
}
2532
}

src/main/java/com/back/domain/board/comment/service/CommentLikeService.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ public CommentLikeResponse cancelLikeComment(Long commentId, Long userId) {
7070
CommentLike commentLike = commentLikeRepository.findByUserIdAndCommentId(userId, commentId)
7171
.orElseThrow(() -> new CustomException(ErrorCode.COMMENT_LIKE_NOT_FOUND));
7272

73+
// 연관관계 제거
74+
comment.removeLike(commentLike);
75+
user.removeCommentLike(commentLike);
76+
7377
// CommentLike 삭제
7478
commentLikeRepository.delete(commentLike);
7579

src/main/java/com/back/domain/board/comment/service/CommentService.java

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,15 @@ public class CommentService {
3838
private final PostRepository postRepository;
3939
private final ApplicationEventPublisher eventPublisher;
4040

41+
// TODO: 연관관계 고려, 메서드 명, 중복 코드 제거, 주석 통일
42+
// TODO: comment 끝나면 post도 해야 함.. entity > DTO > Repo > Service > Controller > Docs 순으로..
4143
/**
4244
* 댓글 생성 서비스
4345
* 1. User 조회
4446
* 2. Post 조회
45-
* 3. Comment 생성
46-
* 4. Comment 저장 및 CommentResponse 반환
47+
* 3. Comment 생성 및 저장
48+
* 4. 댓글 작성 이벤트 발행
49+
* 5. CommentResponse 반환
4750
*/
4851
public CommentResponse createComment(Long postId, CommentRequest request, Long userId) {
4952
// User 조회
@@ -54,10 +57,11 @@ public CommentResponse createComment(Long postId, CommentRequest request, Long u
5457
Post post = postRepository.findById(postId)
5558
.orElseThrow(() -> new CustomException(ErrorCode.POST_NOT_FOUND));
5659

57-
// Comment 생성
58-
Comment comment = new Comment(post, user, request.content());
60+
// CommentCount 증가
61+
post.increaseCommentCount();
5962

60-
// Comment 저장 및 응답 반환
63+
// Comment 생성 및 저장
64+
Comment comment = Comment.createRoot(post, user, request.content());
6165
commentRepository.save(comment);
6266

6367
// 댓글 작성 이벤트 발행
@@ -164,6 +168,10 @@ public CommentResponse updateComment(Long postId, Long commentId, CommentRequest
164168
* 4. Comment 삭제
165169
*/
166170
public void deleteComment(Long postId, Long commentId, Long userId) {
171+
// User 조회
172+
User user = userRepository.findById(userId)
173+
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));
174+
167175
// Post 조회
168176
Post post = postRepository.findById(postId)
169177
.orElseThrow(() -> new CustomException(ErrorCode.POST_NOT_FOUND));
@@ -177,6 +185,11 @@ public void deleteComment(Long postId, Long commentId, Long userId) {
177185
throw new CustomException(ErrorCode.COMMENT_NO_PERMISSION);
178186
}
179187

188+
// 연관관계 제거
189+
post.removeComment(comment);
190+
user.removeComment(comment);
191+
192+
// Comment 삭제
180193
commentRepository.delete(comment);
181194
}
182195

src/main/java/com/back/domain/board/post/entity/Post.java

Lines changed: 42 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,16 @@
99

1010
import java.util.ArrayList;
1111
import java.util.List;
12-
import java.util.regex.Matcher;
13-
import java.util.regex.Pattern;
1412

1513
@Entity
1614
@Getter
1715
@NoArgsConstructor
1816
public class Post extends BaseEntity {
1917
@ManyToOne(fetch = FetchType.LAZY)
20-
@JoinColumn(name = "user_id")
18+
@JoinColumn(name = "user_id", nullable = false)
2119
private User user;
2220

21+
@Column(nullable = false)
2322
private String title;
2423

2524
@Column(nullable = false, columnDefinition = "TEXT")
@@ -28,7 +27,6 @@ public class Post extends BaseEntity {
2827
@Column(length = 500)
2928
private String thumbnailUrl;
3029

31-
// TODO: 추후 PostRepositoryImpl#searchPosts 로직 개선 필요, ERD에도 반영할 것
3230
@Column(nullable = false)
3331
private Long likeCount = 0L;
3432

@@ -51,73 +49,94 @@ public class Post extends BaseEntity {
5149
private List<Comment> comments = new ArrayList<>();
5250

5351
// -------------------- 생성자 --------------------
54-
public Post(User user, String title, String content) {
55-
this.user = user;
56-
this.title = title;
57-
this.content = content;
58-
this.thumbnailUrl = null;
59-
}
60-
6152
public Post(User user, String title, String content, String thumbnailUrl) {
6253
this.user = user;
6354
this.title = title;
6455
this.content = content;
6556
this.thumbnailUrl = thumbnailUrl;
57+
user.addPost(this);
58+
}
59+
60+
// -------------------- 연관관계 편의 메서드 --------------------
61+
public void addPostCategoryMapping(PostCategoryMapping mapping) {
62+
this.postCategoryMappings.add(mapping);
63+
}
64+
65+
public void addLike(PostLike like) {
66+
this.postLikes.add(like);
67+
}
68+
69+
public void removeLike(PostLike like) {
70+
this.postLikes.remove(like);
71+
}
72+
73+
public void addBookmark(PostBookmark bookmark) {
74+
this.postBookmarks.add(bookmark);
75+
}
76+
77+
public void removeBookmark(PostBookmark bookmark) {
78+
this.postBookmarks.remove(bookmark);
79+
}
80+
81+
public void addComment(Comment comment) {
82+
this.comments.add(comment);
83+
}
84+
85+
public void removeComment(Comment comment) {
86+
this.comments.remove(comment);
6687
}
6788

6889
// -------------------- 비즈니스 메서드 --------------------
69-
// 게시글 업데이트
90+
/** 게시글 내용 수정 */
7091
public void update(String title, String content) {
7192
this.title = title;
7293
this.content = content;
7394
}
7495

75-
// 카테고리 업데이트
96+
/** 카테고리 일괄 업데이트 */
7697
public void updateCategories(List<PostCategory> categories) {
7798
this.postCategoryMappings.clear();
78-
categories.forEach(category ->
79-
this.postCategoryMappings.add(new PostCategoryMapping(this, category))
80-
);
99+
categories.forEach(category -> new PostCategoryMapping(this, category));
81100
}
82101

83-
// 좋아요 수 증가
102+
/** 좋아요 수 증가 */
84103
public void increaseLikeCount() {
85104
this.likeCount++;
86105
}
87106

88-
// 좋아요 수 감소
107+
/** 좋아요 수 감소 */
89108
public void decreaseLikeCount() {
90109
if (this.likeCount > 0) {
91110
this.likeCount--;
92111
}
93112
}
94113

95-
// 북마크 수 증가
114+
/** 북마크 수 증가 */
96115
public void increaseBookmarkCount() {
97116
this.bookmarkCount++;
98117
}
99118

100-
// 북마크 수 감소
119+
/** 북마크 수 감소 */
101120
public void decreaseBookmarkCount() {
102121
if (this.bookmarkCount > 0) {
103122
this.bookmarkCount--;
104123
}
105124
}
106125

107-
// 댓글 수 증가
126+
/** 댓글 수 증가 */
108127
public void increaseCommentCount() {
109128
this.commentCount++;
110129
}
111130

112-
// 댓글 수 감소
131+
/** 댓글 수 감소 */
113132
public void decreaseCommentCount() {
114133
if (this.commentCount > 0) {
115134
this.commentCount--;
116135
}
117136
}
118137

119138
// -------------------- 헬퍼 메서드 --------------------
120-
// 게시글에 연결된 카테고리 목록 조회
139+
/** 게시글에 연결된 카테고리 목록 조회 */
121140
public List<PostCategory> getCategories() {
122141
return postCategoryMappings.stream()
123142
.map(PostCategoryMapping::getCategory)

src/main/java/com/back/domain/board/post/entity/PostBookmark.java

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,23 @@
1010
@Entity
1111
@Getter
1212
@NoArgsConstructor
13-
@AllArgsConstructor
1413
@Table(
15-
uniqueConstraints = {
16-
@UniqueConstraint(columnNames = {"post_id", "user_id"})
17-
}
14+
uniqueConstraints = @UniqueConstraint(columnNames = {"post_id", "user_id"})
1815
)
1916
public class PostBookmark extends BaseEntity {
2017
@ManyToOne(fetch = FetchType.LAZY)
21-
@JoinColumn(name = "post_id")
18+
@JoinColumn(name = "post_id", nullable = false)
2219
private Post post;
2320

2421
@ManyToOne(fetch = FetchType.LAZY)
25-
@JoinColumn(name = "user_id")
22+
@JoinColumn(name = "user_id", nullable = false)
2623
private User user;
24+
25+
// -------------------- 생성자 --------------------
26+
public PostBookmark(Post post, User user) {
27+
this.post = post;
28+
this.user = user;
29+
post.addBookmark(this);
30+
user.addPostBookmark(this);
31+
}
2732
}

0 commit comments

Comments
 (0)