Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JPA2] 이혜원 #22

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.example.blog.domain.comment.Controller;


import com.example.blog.domain.comment.dto.CommentReq;
import com.example.blog.domain.comment.dto.CommentRes;
import com.example.blog.domain.comment.service.CommentService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comments")
public class CommentController {

private final CommentService commentService;

public CommentController(CommentService commentService) {
this.commentService = commentService;
}

@PostMapping
public ResponseEntity<CommentRes> createComment(@RequestBody CommentReq commentReq) {
CommentRes comment = commentService.createComment(commentReq);
return ResponseEntity.ok(comment);
}

@GetMapping("/post/{postId}")
public ResponseEntity<List<CommentRes>> getCommentsByPostId(@PathVariable Long postId) {
List<CommentRes> comments = commentService.getCommentsByPostId(postId);
return ResponseEntity.ok(comments);
}

@GetMapping("/user/{userId}")
public ResponseEntity<List<CommentRes>> getCommentsByUserId(@PathVariable Long userId) {
List<CommentRes> comments = commentService.getCommentsByUserId(userId);
return ResponseEntity.ok(comments);
}

@PutMapping("/{commentId}")
public ResponseEntity<CommentRes> updateComment(@PathVariable Long commentId, @RequestBody CommentReq commentReq) {
CommentRes updatedComment = commentService.updateComment(commentId, commentReq.getContent());
return ResponseEntity.ok(updatedComment);
}

@DeleteMapping("/{commentId}")
public ResponseEntity<Void> deleteComment(@PathVariable Long commentId) {
commentService.deleteComment(commentId);
return ResponseEntity.noContent().build();
}

// 댓글 좋아요
@PostMapping("/{commentId}/like")
public ResponseEntity<Void> likeComment(@PathVariable Long commentId, @RequestParam Long userId) {
commentService.likeComment(commentId, userId);
return ResponseEntity.ok().build();
}

// 댓글 좋아요 취소
@PostMapping("/{commentId}/unlike")
public ResponseEntity<Void> unlikeComment(@PathVariable Long commentId, @RequestParam Long userId) {
commentService.unlikeComment(commentId, userId);
return ResponseEntity.ok().build();
}

}
74 changes: 74 additions & 0 deletions src/main/java/com/example/blog/domain/comment/domain/Comment.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.example.blog.domain.comment.domain;

import com.example.blog.domain.post.domain.Post;
import com.example.blog.domain.user.domain.User;
import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.HashSet;
import java.util.Set;

@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
public class Comment {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private Post post;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;

@Column(nullable = false)
private String content;

// 댓글 좋아요 기능 추가
@Column(columnDefinition = "integer default 0", nullable = false)
private int likes;

@ManyToMany
@JoinTable(
name = "comment_likes",
joinColumns = @JoinColumn(name = "comment_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
private Set<User> likedUsers = new HashSet<>();

@Builder
public Comment(Post post, User user, String content) {
this.post = post;
this.user = user;
this.content = content;
}

public void update(String content) {
this.content = content;
}


// 댓글 좋아요
public void like(User user) {
if (likedUsers.add(user)) {
this.likes++;
}
}

// 댓글 좋아요 취소
public void unlike(User user) {
if (likedUsers.remove(user)) {
this.likes--;
}
}



}
12 changes: 12 additions & 0 deletions src/main/java/com/example/blog/domain/comment/dto/CommentReq.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.example.blog.domain.comment.dto;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class CommentReq {
private Long postId;
private Long userId;
private String content;
}
23 changes: 23 additions & 0 deletions src/main/java/com/example/blog/domain/comment/dto/CommentRes.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.blog.domain.comment.dto;

import com.example.blog.domain.comment.domain.Comment;
import lombok.Getter;

@Getter
public class CommentRes {
private Long id;
private String content;
private String username;
private Long postId;

public CommentRes(Comment comment) {
this.id = comment.getId();
this.content = comment.getContent();
this.username = comment.getUser().getUsername();
this.postId = comment.getPost().getId();
}

public static CommentRes fromEntity(Comment comment) {
return new CommentRes(comment);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.blog.domain.comment.repository;

import com.example.blog.domain.comment.domain.Comment;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface CommentRepository extends JpaRepository<Comment, Long> {
List<Comment> findByPostId(Long postId);
List<Comment> findByUserId(Long userId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package com.example.blog.domain.comment.service;

import com.example.blog.domain.comment.domain.Comment;
import com.example.blog.domain.comment.dto.CommentReq;
import com.example.blog.domain.comment.dto.CommentRes;
import com.example.blog.domain.comment.repository.CommentRepository;
import com.example.blog.domain.post.domain.Post;
import com.example.blog.domain.post.repository.PostRepository;
import com.example.blog.domain.user.domain.User;
import com.example.blog.domain.user.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentService {

private final CommentRepository commentRepository;
private final PostRepository postRepository;
private final UserRepository userRepository;

public CommentService(CommentRepository commentRepository, PostRepository postRepository, UserRepository userRepository) {
this.commentRepository = commentRepository;
this.postRepository = postRepository;
this.userRepository = userRepository;
}

@Transactional
public CommentRes createComment(CommentReq commentReq) {
Post post = postRepository.findById(commentReq.getPostId()).orElseThrow(() -> new IllegalArgumentException("Invalid post ID"));
User user = userRepository.findById(commentReq.getUserId()).orElseThrow(() -> new IllegalArgumentException("Invalid user ID"));
Comment comment = Comment.builder().post(post).user(user).content(commentReq.getContent()).build();
return CommentRes.fromEntity(commentRepository.save(comment));
}

@Transactional(readOnly = true)
public List<CommentRes> getCommentsByPostId(Long postId) {
List<Comment> comments = commentRepository.findByPostId(postId);
return comments.stream().map(CommentRes::fromEntity).collect(Collectors.toList());
}

@Transactional(readOnly = true)
public List<CommentRes> getCommentsByUserId(Long userId) {
List<Comment> comments = commentRepository.findByUserId(userId);
return comments.stream().map(CommentRes::fromEntity).collect(Collectors.toList());
}

@Transactional
public CommentRes updateComment(Long commentId, String content) {
Comment comment = commentRepository.findById(commentId).orElseThrow(() -> new IllegalArgumentException("Invalid comment ID"));
comment.update(content);
return CommentRes.fromEntity(commentRepository.save(comment));
}

@Transactional
public void deleteComment(Long commentId) {
Comment comment = commentRepository.findById(commentId).orElseThrow(() -> new IllegalArgumentException("Invalid comment ID"));
commentRepository.delete(comment);
}

// 댓글 좋아요
@Transactional
public void likeComment(Long commentId, Long userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("해당 유저 없음"));
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new IllegalArgumentException("해당 댓글 없음"));

comment.like(user);
commentRepository.save(comment);
}

// 댓글 좋아요 취소
@Transactional
public void unlikeComment(Long commentId, Long userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("해당 유저 없음"));
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new IllegalArgumentException("해당 댓글 없음"));

comment.unlike(user);
commentRepository.save(comment);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package com.example.blog.domain.post.Controller;

import com.example.blog.domain.post.domain.Post;
import com.example.blog.domain.post.service.PostService;
import com.example.blog.domain.post.dto.PostReq;
import com.example.blog.domain.post.dto.PostRes;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/posts")
public class PostController {
private final PostService postService;

@GetMapping("")
public ResponseEntity<List<PostRes>> getAllPosts() {
List<Post> posts = postService.getAllPosts();
List<PostRes> postResponses = posts.stream()
.map(PostRes::fromEntity)
.collect(Collectors.toList());
return ResponseEntity.ok(postResponses);
}

@GetMapping("/{postId}")
public ResponseEntity<?> getPost(@PathVariable Long postId) {
postService.updateView(postId); // 조회수 증가
Post post = postService.getPost(postId);
PostRes postRes = PostRes.fromEntity(post);
return ResponseEntity.ok(postRes);
}

@PostMapping("")
public ResponseEntity<?> createPost(@RequestBody PostReq postReq) {
Post post = Post.builder()
.title(postReq.title())
.content(postReq.content())
.build();
Post createdPost = postService.createPost(postReq.userId(), post);
PostRes postRes = PostRes.fromEntity(createdPost);
return ResponseEntity.ok(postRes);
}

@PutMapping("/{postId}")
public ResponseEntity<?> updatePost(@PathVariable Long postId, @RequestBody PostReq postReq) {
Post post = Post.builder()
.title(postReq.title())
.content(postReq.content())
.build();
Post updatedPost = postService.updatePost(postId, post);
PostRes postRes = PostRes.fromEntity(updatedPost);
return ResponseEntity.ok(postRes);
}

@DeleteMapping("/{postId}")
public ResponseEntity<?> deletePost(@PathVariable Long postId) {
postService.deletePost(postId);
return ResponseEntity.ok().build();
}
@RestController
public class SearchController {

// 검색 기능 : 제목
@GetMapping("/search/title")
public ResponseEntity<?> searchByTitle(@RequestParam String titleKeyword) {
List<Post> searchList = postService.searchByTitle(titleKeyword);
if (searchList.isEmpty()) {
return ResponseEntity.status(404).body("해당 게시물 없음!");
}
List<PostRes> postResponses = searchList.stream()
.map(PostRes::fromEntity)
.collect(Collectors.toList());
return ResponseEntity.ok(postResponses);
}

// 검색 기능 : 내용
@GetMapping("/search/content")
public ResponseEntity<?> searchByContent(@RequestParam String contentKeyword) {
List<Post> searchList = postService.searchByContent(contentKeyword);
if (searchList.isEmpty()) {
return ResponseEntity.status(404).body("해당 내용 없음!");
}
List<PostRes> postResponses = searchList.stream()
.map(PostRes::fromEntity)
.collect(Collectors.toList());
return ResponseEntity.ok(postResponses);
}

// 검색 기능 : 작성자
@GetMapping("/search/username")
public ResponseEntity<?> searchByUsername(@RequestParam String usernameKeyword) {
List<Post> searchList = postService.searchByUsername(usernameKeyword);
if (searchList.isEmpty()) {
return ResponseEntity.status(404).body("해당 작성자 없음!");
}
List<PostRes> postResponses = searchList.stream()
.map(PostRes::fromEntity)
.collect(Collectors.toList());
return ResponseEntity.ok(postResponses);
}
}

}
Loading