Skip to content

Commit feb9c7a

Browse files
authored
Ref: Unique Key 충돌 및 flush 타이밍 문제 해결 (#263)
1 parent fcf5718 commit feb9c7a

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

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

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ public void addPostCategoryMapping(PostCategoryMapping mapping) {
6262
this.postCategoryMappings.add(mapping);
6363
}
6464

65+
public void removePostCategoryMapping(PostCategoryMapping mapping) {
66+
this.postCategoryMappings.remove(mapping);
67+
}
68+
6569
public void addLike(PostLike like) {
6670
this.postLikes.add(like);
6771
}
@@ -93,11 +97,23 @@ public void update(String title, String content) {
9397
this.content = content;
9498
}
9599

96-
// TODO: 진짜로 바뀐 카테고리만 추가/삭제하도록 개선
97100
/** 카테고리 일괄 업데이트 */
98-
public void updateCategories(List<PostCategory> categories) {
99-
this.postCategoryMappings.clear();
100-
categories.forEach(category -> new PostCategoryMapping(this, category));
101+
public void updateCategories(List<PostCategory> newCategories) {
102+
List<PostCategory> currentCategories = this.getCategories();
103+
104+
// 제거 대상
105+
List<PostCategoryMapping> toRemove = this.getPostCategoryMappings().stream()
106+
.filter(mapping -> !newCategories.contains(mapping.getCategory()))
107+
.toList();
108+
109+
// 추가 대상
110+
List<PostCategory> toAdd = newCategories.stream()
111+
.filter(category -> !currentCategories.contains(category))
112+
.toList();
113+
114+
// 실행
115+
toRemove.forEach(this::removePostCategoryMapping);
116+
toAdd.forEach(category -> new PostCategoryMapping(this, category));
101117
}
102118

103119
/** 좋아요 수 증가 */

src/main/java/com/back/domain/board/post/service/PostService.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,17 +49,18 @@ public PostResponse createPost(PostRequest request, Long userId) {
4949
// Post 생성
5050
Post post = new Post(user, request.title(), request.content(), request.thumbnailUrl());
5151

52+
// Post 저장
53+
Post saved = postRepository.save(post);
54+
5255
// Category 매핑
5356
if (request.categoryIds() != null) {
5457
List<PostCategory> categories = postCategoryRepository.findAllById(request.categoryIds());
5558
if (categories.size() != request.categoryIds().size()) {
5659
throw new CustomException(ErrorCode.CATEGORY_NOT_FOUND);
5760
}
58-
post.updateCategories(categories);
61+
saved.updateCategories(categories);
5962
}
6063

61-
// Post 저장 및 응답 반환
62-
Post saved = postRepository.save(post);
6364
return PostResponse.from(saved);
6465
}
6566

0 commit comments

Comments
 (0)