Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,6 @@ out/

### VS Code ###
.vscode/

# .gitignore 파일에 추가
application.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
package com.example.springhw32.controller;

import com.example.springhw32.dto.CommentDto;
import com.example.springhw32.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

private final CommentService commentService;

// 댓글 작성
@PostMapping("/{postId}")
public CommentDto createComment(@RequestBody CommentDto commentDto, @PathVariable Long postId) {
return commentService.createComment(commentDto, postId);
}

// 특정 게시물에 달린 모든 댓글 조회
@GetMapping("/{postId}")
public List<CommentDto> getAllCommentsByPostId(@PathVariable Long postId) {
return commentService.getAllCommentsByPostId(postId);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,39 @@
package com.example.springhw32.controller;

import com.example.springhw32.dto.PostDto;
import com.example.springhw32.service.PostService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/posts")
@RequiredArgsConstructor
public class PostController {

private final PostService postService;

// 글 작성
@PostMapping
public PostDto createPost(@RequestBody PostDto postDto, @RequestParam String writer) {
return postService.createPost(postDto, writer);
}
// 최신순 글 조회
@GetMapping
public List<PostDto> getPostsSortedByDate() {
return postService.getPostsSortedByDate();
}

// 작성자 글 조회
@GetMapping("/{writer}")
public List<PostDto> getPostsByWriter(@PathVariable String writer) {
return postService.getPostsByWriter(writer);
}

// 댓글 많은 순 글 조회
@GetMapping("/comments")
public List<PostDto> getPostsSortedByComments() {
return postService.getPostsSortedByComments();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
package com.example.springhw32.controller;

import com.example.springhw32.dto.UserDto;
import com.example.springhw32.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/users")
public class UserController {

}
private final UserService userService;

@PostMapping
public UserDto join(@ModelAttribute UserDto userDto) {
return userService.join(userDto);
}

@PostMapping("/login")
public String login(@ModelAttribute UserDto userDto) {
return userService.login(userDto);
}
}
11 changes: 11 additions & 0 deletions src/main/java/com/example/springhw32/dto/CommentDto.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
package com.example.springhw32.dto;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class CommentDto {
private Long commentId;

private Long postId;

private Long userId;

private String content;
}
19 changes: 19 additions & 0 deletions src/main/java/com/example/springhw32/dto/PostDto.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
package com.example.springhw32.dto;

import lombok.Getter;
import lombok.Setter;

import java.time.LocalDateTime;

@Getter
@Setter
public class PostDto {
private Long postId;

private String title;

private String content;

private String writer;

private Long commentCount;

private LocalDateTime createdAt;

private LocalDateTime updatedAt;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

createdAt를 넣지 않은 이유가 모야?
postId를 넣은 이유는 모야?

Copy link
Author

@HyerimH HyerimH Oct 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

createdAt을 클라이언트에 보낼 필요 없다구 생각했고
postId는 나중에 삭제나 업데이트 같은 기능 추가할 때 식별하기 위해 넣었슴다

16 changes: 15 additions & 1 deletion src/main/java/com/example/springhw32/dto/UserDto.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
package com.example.springhw32.dto;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
public class UserDto {
private Long userId;

private String username;

private String password;

private String nickname;

}
}
20 changes: 20 additions & 0 deletions src/main/java/com/example/springhw32/entity/Comment.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
package com.example.springhw32.entity;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

@Entity
@Getter
@Setter
public class Comment {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long commentId;

@Column(nullable = false)
private String content;

@ManyToOne
@JoinColumn(name = "userId", nullable = false)
private User user;

@ManyToOne
private Post post;
}
27 changes: 27 additions & 0 deletions src/main/java/com/example/springhw32/entity/Post.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
package com.example.springhw32.entity;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDateTime;

@Getter
@Setter
@Entity
public class Post {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long postId;

@ManyToOne
private User user;

@Column(nullable = false)
private String title;

@Column(nullable = false)
private String content;

private Long commentCount = 0L;

private LocalDateTime createdAt;

private LocalDateTime updatedAt;
}
22 changes: 21 additions & 1 deletion src/main/java/com/example/springhw32/entity/User.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
package com.example.springhw32.entity;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

@Entity
@Getter
@Setter
public class User {

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

@Column(nullable = false, unique = true)
private String username;

@Column(nullable = false)
private String password;

@Column(nullable = false, unique = true)
private String nickname;

}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EndOfFile 설정하면
image
이거 안 뜨게 할 수 있음

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package com.example.springhw32.repository;

public interface CommentRepository {
import com.example.springhw32.entity.Comment;
import com.example.springhw32.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

}
import java.util.List;

public interface CommentRepository extends JpaRepository<Comment, Long> {
// 특정 게시물에 달린 모든 댓글 조회
List<Comment> findByPost_PostId(Long postId);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
package com.example.springhw32.repository;

public interface PostRepository {
import com.example.springhw32.entity.Post;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface PostRepository extends JpaRepository<Post, Long> {
List<Post> findByUser_Nickname(String nickname);
List<Post> findAllByOrderByCreatedAtDesc();
List<Post> findAllByOrderByCommentCountDesc();
}

Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
package com.example.springhw32.repository;

public interface UserRepository {
import com.example.springhw32.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);

boolean existsByUsername(String username);

boolean existsByNickname(String nickname);

Optional<User> findByNickname(String nickname);
}
56 changes: 56 additions & 0 deletions src/main/java/com/example/springhw32/service/CommentService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,61 @@
package com.example.springhw32.service;

import com.example.springhw32.dto.CommentDto;
import com.example.springhw32.entity.Comment;
import com.example.springhw32.entity.Post;
import com.example.springhw32.entity.User;
import com.example.springhw32.repository.CommentRepository;
import com.example.springhw32.repository.PostRepository;
import com.example.springhw32.repository.UserRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

@Service
@RequiredArgsConstructor
public class CommentService {

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

@Transactional
public CommentDto createComment(CommentDto commentDto, Long postId) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new NoSuchElementException("Post not found"));

User user = userRepository.findById(commentDto.getUserId())
.orElseThrow(() -> new NoSuchElementException("User not found"));

Comment comment = new Comment();
comment.setContent(commentDto.getContent());
comment.setUser(user);
comment.setPost(post);
commentRepository.save(comment);
post.setCommentCount(post.getCommentCount() + 1L);
postRepository.save(post);
return mapToDto(comment);
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

혹시 댓글 작성해서 댓글 수 올라가는 로직 어디에 작성했어?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

추가했습니다 하하ㅏ



// 특정 게시물에 달린 모든 댓글 조회
public List<CommentDto> getAllCommentsByPostId(Long postId) {
return commentRepository.findByPost_PostId(postId).stream()
.map(this::mapToDto)
.collect(Collectors.toList());
}

// Comment -> CommentDto 변환
private CommentDto mapToDto(Comment comment) {
CommentDto dto = new CommentDto();
dto.setCommentId(comment.getCommentId());
dto.setPostId(comment.getPost().getPostId());
dto.setUserId(comment.getUser().getId());
dto.setContent(comment.getContent());
return dto;
}
}
Loading