Skip to content

Commit 2004fd1

Browse files
authored
Chore: 샘플 데이터 및 Post 엔티티 확장 추가 (#204) (#206)
1 parent 14a756e commit 2004fd1

File tree

4 files changed

+123
-21
lines changed

4 files changed

+123
-21
lines changed

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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,12 @@ public class Post extends BaseEntity {
2626
@Column(nullable = false)
2727
private Long likeCount = 0L;
2828

29+
@Column(nullable = false)
30+
private Long bookmarkCount = 0L;
31+
32+
@Column(nullable = false)
33+
private Long commentCount = 0L;
34+
2935
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
3036
private List<PostCategoryMapping> postCategoryMappings = new ArrayList<>();
3137

@@ -72,6 +78,30 @@ public void decreaseLikeCount() {
7278
}
7379
}
7480

81+
// 북마크 수 증가
82+
public void increaseBookmarkCount() {
83+
this.bookmarkCount++;
84+
}
85+
86+
// 북마크 수 감소
87+
public void decreaseBookmarkCount() {
88+
if (this.bookmarkCount > 0) {
89+
this.bookmarkCount--;
90+
}
91+
}
92+
93+
// 댓글 수 증가
94+
public void increaseCommentCount() {
95+
this.commentCount++;
96+
}
97+
98+
// 댓글 수 감소
99+
public void decreaseCommentCount() {
100+
if (this.commentCount > 0) {
101+
this.commentCount--;
102+
}
103+
}
104+
75105
// -------------------- 헬퍼 메서드 --------------------
76106
// 게시글에 연결된 카테고리 목록 조회
77107
public List<PostCategory> getCategories() {

src/main/java/com/back/domain/board/post/repository/PostCategoryRepository.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
import org.springframework.data.jpa.repository.JpaRepository;
55
import org.springframework.stereotype.Repository;
66

7+
import java.util.List;
8+
79
@Repository
810
public interface PostCategoryRepository extends JpaRepository<PostCategory, Long> {
911
boolean existsByName(String name);
12+
List<PostCategory> findAllByNameIn(List<String> categoryNames);
1013
}
Lines changed: 88 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
package com.back.global.initData;
22

3+
import com.back.domain.board.comment.entity.Comment;
4+
import com.back.domain.board.comment.repository.CommentRepository;
5+
import com.back.domain.board.post.entity.Post;
6+
import com.back.domain.board.post.entity.PostCategory;
7+
import com.back.domain.board.post.repository.PostCategoryRepository;
8+
import com.back.domain.board.post.repository.PostRepository;
39
import com.back.domain.user.entity.User;
410
import com.back.domain.user.entity.UserProfile;
511
import com.back.domain.user.entity.UserStatus;
@@ -13,51 +19,112 @@
1319
import org.springframework.security.crypto.password.PasswordEncoder;
1420
import org.springframework.transaction.annotation.Transactional;
1521

22+
import java.util.List;
23+
1624
@Configuration
25+
@Profile("default")
1726
@RequiredArgsConstructor
1827
public class DevInitData {
1928
private final UserRepository userRepository;
29+
private final PostRepository postRepository;
30+
private final CommentRepository commentRepository;
31+
private final PostCategoryRepository postCategoryRepository;
2032
private final PasswordEncoder passwordEncoder;
2133
private final Environment environment;
34+
2235
@Bean
2336
ApplicationRunner DevInitDataApplicationRunner() {
2437
return args -> {
25-
String activeProfile = environment.getProperty("spring.profiles.active", "none");
26-
if (!"default".equals(activeProfile)) {
27-
return; // default 환경이 아니면 실행하지 않음
28-
}
29-
initUsers();
38+
initUsersAndPostsAndComments();
3039
};
3140
}
3241

3342
@Transactional
34-
public void initUsers() {
43+
public void initUsersAndPostsAndComments() {
3544
if (userRepository.count() == 0) {
36-
User admin = User.createAdmin(
37-
"admin",
38-
39-
passwordEncoder.encode("12345678!")
40-
);
45+
// -------------------- 유저 --------------------
46+
User admin = User.createAdmin("admin", "[email protected]", passwordEncoder.encode("12345678!"));
4147
admin.setUserProfile(new UserProfile(admin, "관리자", null, null, null, 0));
4248
userRepository.save(admin);
4349

44-
User user1 = User.createUser(
45-
"user1",
46-
47-
passwordEncoder.encode("12345678!")
48-
);
50+
User user1 = User.createUser("user1", "[email protected]", passwordEncoder.encode("12345678!"));
4951
user1.setUserProfile(new UserProfile(user1, "사용자1", null, null, null, 0));
5052
user1.setUserStatus(UserStatus.ACTIVE);
5153
userRepository.save(user1);
5254

53-
User user2 = User.createUser(
54-
"user2",
55-
56-
passwordEncoder.encode("12345678!")
57-
);
55+
User user2 = User.createUser("user2", "[email protected]", passwordEncoder.encode("12345678!"));
5856
user2.setUserProfile(new UserProfile(user2, "사용자2", null, null, null, 0));
5957
user2.setUserStatus(UserStatus.ACTIVE);
6058
userRepository.save(user2);
59+
60+
User user3 = User.createUser("user3", "[email protected]", passwordEncoder.encode("12345678!"));
61+
user3.setUserProfile(new UserProfile(user3, "사용자3", null, null, null, 0));
62+
user3.setUserStatus(UserStatus.ACTIVE);
63+
userRepository.save(user3);
64+
65+
// -------------------- 게시글 --------------------
66+
createSamplePosts(user1, user2, user3);
67+
}
68+
}
69+
70+
private void createSamplePosts(User user1, User user2, User user3) {
71+
Post post1 = new Post(user1,
72+
"[백엔드] 같이 스프링 공부하실 분 구해요!",
73+
"매주 토요일 오후 2시에 온라인으로 스터디 진행합니다.\n교재는 '스프링 완전정복'을 사용할 예정입니다.");
74+
attachCategories(post1, List.of("백엔드", "직장인", "5~10명"));
75+
76+
Post post2 = new Post(user2,
77+
"[프론트엔드] 리액트 입문 스터디원 모집",
78+
"리액트 교재를 같이 읽고 실습해보는 스터디입니다. GitHub로 코드 리뷰도 진행합니다.");
79+
attachCategories(post2, List.of("프론트엔드", "대학생", "2~4명"));
80+
81+
Post post3 = new Post(user2,
82+
"[CS] 컴퓨터 구조 스터디",
83+
"운영체제, 네트워크, 컴퓨터 구조 기본 개념을 함께 정리해요.\n스터디원 5명 정도 모집합니다.");
84+
attachCategories(post3, List.of("CS", "취준생", "5~10명"));
85+
86+
Post post4 = new Post(user3,
87+
"[알고리즘] 백준 골드 도전 스터디",
88+
"매주 3문제씩 풀이, 코드 리뷰 및 전략 공유합니다.\n실력 향상을 목표로 합니다!");
89+
attachCategories(post4, List.of("알고리즘", "대학생", "5~10명"));
90+
91+
Post post5 = new Post(user1,
92+
"[영어 회화] 직장인 아침 스터디",
93+
"출근 전 30분, 영어회화 연습 스터디입니다.\n줌으로 진행하고 서로 피드백 나눠요 :)");
94+
attachCategories(post5, List.of("영어 회화", "직장인", "2~4명"));
95+
96+
postRepository.saveAll(List.of(post1, post2, post3, post4, post5));
97+
98+
// -------------------- 댓글 --------------------
99+
createSampleComments(user1, user2, user3, post1, post2, post3);
100+
}
101+
102+
private void createSampleComments(User user1, User user2, User user3, Post post1, Post post2, Post post3) {
103+
// Post1에 댓글
104+
Comment comment1 = new Comment(post1, user2, "저도 참여하고 싶어요!");
105+
Comment reply1 = new Comment(post1, user1, "좋아요 :) 디스코드 링크 드릴게요.", comment1);
106+
107+
// Post2에 댓글
108+
Comment comment2 = new Comment(post2, user3, "스터디 모집 기간은 언제까지인가요?");
109+
Comment reply2 = new Comment(post2, user2, "이번 주 일요일까지 받을 예정이에요.", comment2);
110+
111+
// Post3에 댓글
112+
Comment comment3 = new Comment(post3, user1, "CS는 항상 중요하죠 💪");
113+
114+
commentRepository.saveAll(List.of(comment1, reply1, comment2, reply2, comment3));
115+
116+
// 게시글 commentCount 반영
117+
post1.increaseCommentCount();
118+
post2.increaseCommentCount();
119+
post3.increaseCommentCount();
120+
121+
postRepository.saveAll(List.of(post1, post2, post3));
122+
}
123+
124+
private void attachCategories(Post post, List<String> categoryNames) {
125+
List<PostCategory> categories = postCategoryRepository.findAllByNameIn(categoryNames);
126+
if (!categories.isEmpty()) {
127+
post.updateCategories(categories);
61128
}
62129
}
63130
}

src/test/java/com/back/domain/notification/controller/NotificationControllerTest.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.springframework.http.MediaType;
2626
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
2727
import org.springframework.security.core.authority.SimpleGrantedAuthority;
28+
import org.springframework.test.context.ActiveProfiles;
2829
import org.springframework.test.context.bean.override.mockito.MockitoBean;
2930
import org.springframework.test.web.servlet.MockMvc;
3031
import org.springframework.test.web.servlet.ResultActions;
@@ -39,6 +40,7 @@
3940

4041
@SpringBootTest
4142
@AutoConfigureMockMvc
43+
@ActiveProfiles("test")
4244
class NotificationControllerTest {
4345

4446
@Autowired

0 commit comments

Comments
 (0)