Skip to content
22 changes: 3 additions & 19 deletions src/main/java/com/example/devSns/controllers/PostController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

import com.example.devSns.dto.PostDTO;
import com.example.devSns.dto.PostResponse;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
Expand All @@ -23,9 +21,9 @@ public ResponseEntity<List<PostResponse>> showPosts() {
return new ResponseEntity<>(posts, HttpStatus.OK);
}

@GetMapping("/show/{username}")
public ResponseEntity<List<PostResponse>> showPost(@PathVariable String username) {
List<PostResponse> post = postService.findByUsername(username);
@GetMapping("/show/{userID}")
public ResponseEntity<List<PostResponse>> showPost(@PathVariable Long userID) {
List<PostResponse> post = postService.findByUserID(userID);
return new ResponseEntity<>(post, HttpStatus.OK);
}

Expand All @@ -46,18 +44,4 @@ public ResponseEntity<String> deletePost(@PathVariable Long id) {
postService.delete(id);
return new ResponseEntity<>("Post deleted", HttpStatus.OK);
}

@ExceptionHandler
public ResponseEntity<String> handleEntityNotFoundException(EntityNotFoundException e) {
ResponseEntity<String> response =
new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
return response;
}

@ExceptionHandler
public ResponseEntity<String> handleDataAccessException(DataAccessException e) {
ResponseEntity<String> response =
new ResponseEntity<>("DB 오류", HttpStatus.INTERNAL_SERVER_ERROR);
return response;
}
}
46 changes: 46 additions & 0 deletions src/main/java/com/example/devSns/controllers/ReplyController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.example.devSns.controllers;

import com.example.devSns.dto.ReplyDTO;
import com.example.devSns.dto.ReplyResponse;
import com.example.devSns.services.ReplyService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping
@RequiredArgsConstructor
public class ReplyController {
private final ReplyService replyService;

@GetMapping("/{postId}/replies")
public ResponseEntity<List<ReplyResponse>> getReplies(@PathVariable long postId) {
List<ReplyResponse> replies = replyService.replyGetAll(postId);
ResponseEntity<List<ReplyResponse>> responseEntity = new ResponseEntity<>(replies, HttpStatus.OK);
return responseEntity;
}

@PostMapping("/{postId}")
public ResponseEntity<ReplyResponse> writeReply(@PathVariable long postId, long userId, ReplyDTO reply) {
ReplyResponse replyResponse = replyService.writeReply(postId, userId, reply);
ResponseEntity<ReplyResponse> responseEntity = new ResponseEntity<>(replyResponse, HttpStatus.OK);
return responseEntity;
}

@PatchMapping("/{postid}")
public ResponseEntity<ReplyResponse> updateReply(@PathVariable long postId, long userId, ReplyDTO reply) {
ReplyResponse replyResponse = replyService.updateReply(postId, userId, reply);
ResponseEntity<ReplyResponse> responseEntity = new ResponseEntity<>(replyResponse, HttpStatus.OK);
return responseEntity;
}

@DeleteMapping("/{postId}")
public ResponseEntity<String> deleteReply(@PathVariable long postId, long userId) {
String deleteCheck = replyService.deleteReply(postId, userId);
ResponseEntity<String> responseEntity = new ResponseEntity<>(deleteCheck, HttpStatus.OK);
return responseEntity;
}
}
14 changes: 13 additions & 1 deletion src/main/java/com/example/devSns/dto/PostDTO.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
package com.example.devSns.dto;

import com.example.devSns.entities.Posts;
import com.example.devSns.entities.Users;

public record PostDTO(
Long userId,
String username,
String content
Comment on lines +7 to 9
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

입력값에 대해 검증이 필요할 것 같아요! @notblank 등을 적용해서 유의미한 입력만 받도록 하면 더 좋을 것 같네요

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

조언 감사합니다!

) { }
) {
public static Posts dtoToEntity(PostDTO postDTO, Users user) {
Posts postEntity = Posts.builder()
.users(user)
.content(postDTO.content())
.build();
return postEntity;
}
}
15 changes: 14 additions & 1 deletion src/main/java/com/example/devSns/dto/PostResponse.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.example.devSns.dto;

import com.example.devSns.entities.Posts;
import com.example.devSns.entities.Users;
import lombok.*;

import java.time.LocalDateTime;
Expand All @@ -12,4 +14,15 @@ public record PostResponse(
Integer like,
LocalDateTime createAt,
LocalDateTime updateAt
) {}
) {
public static PostResponse entityToDto(Posts post) {
return PostResponse.builder()
.id(post.getId())
.username(post.getUsers().getUsername())
.content(post.getContent())
.like(post.getLikeit())
.createAt(post.getCreateat())
.updateAt(post.getUpdateat())
.build();
}
}
19 changes: 19 additions & 0 deletions src/main/java/com/example/devSns/dto/ReplyDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.example.devSns.dto;

import com.example.devSns.entities.Posts;
import com.example.devSns.entities.Replies;
import com.example.devSns.entities.Users;

import java.util.Optional;

public record ReplyDTO(
String comment
) {
public static Replies dtoToEntity(Posts post, Users user, ReplyDTO replyDTO) {
return Replies.builder()
.posts(post)
.users(user)
.reply(replyDTO.comment())
.build();
}
}
19 changes: 19 additions & 0 deletions src/main/java/com/example/devSns/dto/ReplyResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.example.devSns.dto;

import com.example.devSns.entities.Replies;
import lombok.Builder;

@Builder
public record ReplyResponse(
long replyId,
String username,
String comment
) {
public static ReplyResponse entityToDTO(Replies replies) {
return ReplyResponse.builder()
.replyId(replies.getId())
.username(replies.getUsers().getUsername())
.comment(replies.getReply())
.build();
}
}
18 changes: 15 additions & 3 deletions src/main/java/com/example/devSns/entities/Posts.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
Expand All @@ -21,9 +20,10 @@ public class Posts {
@Column
private String content;

@JoinColumn(name = "users_id")
@ManyToOne
Comment on lines +23 to +24
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Post에는 작성한 멤버가 필수로 들어가니 다음과 같이 nullable 조건을 추가하면 더 좋을 것 같아요!

@JoinColumn(name = "users_id", nullable = false)
@ManyToOne(optional = false)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

미처 추가하지 못한 부분을 알려주셔서 감사합니다!

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

제가 자료를 찾다보니 궁금한 점이 있는데, @NotNull과 nullable=false는 어떠한 차이가 있는 건지 여쭤봐도 될까요?

@NotNull
@Column
private String username;
private Users users;

@Column
private int likeit;
Expand All @@ -33,4 +33,16 @@ public class Posts {

@Column
private LocalDateTime updateat;

public void setCreateat(LocalDateTime createat) {
this.createat = createat;
}

public void setUpdateat(LocalDateTime updateat) {
this.updateat = updateat;
}

public void setContent(String content) {
this.content = content;
}
}
42 changes: 42 additions & 0 deletions src/main/java/com/example/devSns/entities/Replies.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.example.devSns.entities;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import lombok.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Builder
public class Replies {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@JoinColumn(name = "posts_id")
@ManyToOne
@NotNull
private Posts posts;

@JoinColumn(name = "users_id")
@ManyToOne
@NotNull
private Users users;

@NotNull
private String reply;

@NotNull
private LocalDateTime createAt;

@NotNull
private LocalDateTime updateAt;

@OneToMany(mappedBy = "posts", cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<Replies> replies = new ArrayList<>();
}
Comment on lines +40 to +42
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

혹시 이건 대댓글 구현 용도로 만들어두신 걸까요? OneToMany 도입 시 list 배열 동시에 관리하기가 어려워서 저는 보통 꼭 필요한 경우가 아니라면 ManyToOne만 사용하는 단방향 연관관계만 적용하는 것을 선호하긴 합니다!

29 changes: 29 additions & 0 deletions src/main/java/com/example/devSns/entities/Users.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.example.devSns.entities;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Date;

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Builder
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@NotNull
private String username;

@NotNull
private Integer age;

private Date birthday;
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
public interface PostRepository extends JpaRepository<Posts, Long> {
public List<Posts> findAll();
public Optional<Posts> findById(Integer id);
public List<Posts> findByUsername(String username);
public List<Posts> findByUsersId(Long userID);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

username대신 unique한 id로 조회하네요! 좋습니다.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

감사합니다!

}
11 changes: 11 additions & 0 deletions src/main/java/com/example/devSns/repositories/ReplyRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.devSns.repositories;

import com.example.devSns.entities.Posts;
import com.example.devSns.entities.Replies;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ReplyRepository extends JpaRepository<Replies, Long> {
public List<Replies> findByPosts(Posts posts);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.example.devSns.repositories;

import com.example.devSns.entities.Users;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<Users, Long> {
public Users findById(long userId);
}
34 changes: 11 additions & 23 deletions src/main/java/com/example/devSns/services/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.example.devSns.dto.PostDTO;
import com.example.devSns.dto.PostResponse;
import com.example.devSns.entities.Posts;
import com.example.devSns.entities.Users;
import com.example.devSns.repositories.UserRepository;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
Expand All @@ -13,33 +15,19 @@
import java.util.ArrayList;
import java.util.List;

import static com.example.devSns.dto.PostDTO.dtoToEntity;
import static com.example.devSns.dto.PostResponse.entityToDto;

@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;

public Posts dtoToEntity(PostDTO postDTO) {
Posts postEntity = Posts.builder()
.username(postDTO.username())
.content(postDTO.content())
.build();
return postEntity;
}

public PostResponse entityToDto(Posts post) {
return PostResponse.builder()
.id(post.getId())
.username(post.getUsername())
.content(post.getContent())
.like(post.getLikeit())
.createAt(post.getCreateat())
.updateAt(post.getUpdateat())
.build();
}
private final UserRepository userRepository;

@Transactional // 트랜잭션 보장
public PostResponse save(PostDTO postDTO) { // post insert
Posts postEntity = dtoToEntity(postDTO);
public PostResponse save(PostDTO postDTO) {
Users user = userRepository.findById(postDTO.userId()).orElseThrow(EntityNotFoundException::new);
Posts postEntity = dtoToEntity(postDTO, user);
postEntity.setCreateat(LocalDateTime.now());
Comment on lines +30 to 31
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

setCreateat을 dtoToEntity에서 진행해도 될 것 같아요!

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

감사합니다! 생각해보니 그렇게 한 번에 처리하는 편이 좀 더 나을 것 같군요

Posts resultEntity = postRepository.save(postEntity);
return entityToDto(resultEntity);
Expand All @@ -56,8 +44,8 @@ public List<PostResponse> findAll() { // 전체 post 조회
}

@Transactional
public List<PostResponse> findByUsername(String username) { // 작성자 기준 post 조회
List<Posts> postsByName = postRepository.findByUsername(username);
public List<PostResponse> findByUserID(Long userID) { // 작성자 기준 post 조회
List<Posts> postsByName = postRepository.findByUsersId(userID);
List<PostResponse> postResponses = new ArrayList<>();
for (Posts post : postsByName) {
postResponses.add(entityToDto(post));
Expand Down
Loading