Search

75. 스프링부트 포토그램 댓글 구현하기 댓글쓰기 완료

이제 실제로 댓글 값을 받아서 DB에 insert 해볼거다
dto 폴더 안에 comment 폴더 생성 후 CommentDto.java 생성
package com.cos.photogramstart.web.dto.comment; import lombok.Data; @Data public class CommentDto { private String content; private int imageId; //toEntity가 필요 없다. }
Java
복사
CommentApiController.java
@PostMapping("/api/comment") public ResponseEntity<?> commentSave(@RequestBody CommentDto commentDto){ System.out.println("Dto : " + commentDto); return null; }
Java
복사
@PostMapping("/api/comment") public ResponseEntity<?> commentSave(@RequestBody CommentDto commentDto, @AuthenticationPrincipal PrincipalDetails principalDetails){ System.out.println("Dto : " + commentDto); commentService.댓글쓰기(commentDto.getContent(), commentDto.getImageId(), principalDetails.getUser().getId()); //content, imageId, userId return null; }
Java
복사
CommentService.java
@Transactional public Comment 댓글쓰기(String content , int imageId, int userId) { return null; }
Java
복사
CommentRepository.java
package com.cos.photogramstart.domain.comment; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; public interface CommentRepository extends JpaRepository<Comment, Integer>{ @Modifying @Query(value = "INSERT INTO comment(content, imageId , userId, createDate) VALUES(:content, :imageId, :userId , now())", nativeQuery = true) Comment mSave(String content, int imageId, int userId); }
Java
복사
CommentService.java
@Transactional public Comment 댓글쓰기(String content , int imageId, int userId) { return commentRepository.mSave(content, imageId, userId); }
Java
복사
CommentApiController.java
@PostMapping("/api/comment") public ResponseEntity<?> commentSave(@RequestBody CommentDto commentDto, @AuthenticationPrincipal PrincipalDetails principalDetails){ Comment comment = commentService.댓글쓰기(commentDto.getContent(), commentDto.getImageId(), principalDetails.getUser().getId()); //content, imageId, userId return new ResponseEntity<>(new CMRespDto<>(1, "댓글쓰기성공", comment), HttpStatus.CREATED); }
Java
복사
java.lang.IllegalArgumentException: Modifying queries can only use void or int/Integer as return type! Offending method: public abstract com.cos.photogramstart.domain.comment.Comment com.cos.photogramstart.domain.comment.CommentRepository.mSave(java.lang.String,int,int) at org.springframework.util.Assert.isTrue(Assert.java:121) ~[spring-core-5.3.6.jar:5.3.6]
Java
복사
댓글 쓰기 누르면 오류가 나는데 CommentRepository.java에서 Comment로 결과값을 받아서 오류가 났다
Comment 말고 int로 받아줘야하는데 그러면 문제가
컨트롤러단에서도 Comment로 받을 수가 없다. 그러면 comment를 리턴해줄수가 없다.
그러면 프라이머리 키를 알수가없다
나중에 댓글을 삭제해줄때 코멘트의 아이디를 몰라서 삭제를 할 수가없다
코멘트의 아이디를 받을려면 네이티브 쿼리로 만들면 안된다.
그러면 JPA가 갖고있는 레파지토리를 사용해야한다.
CommentService.java
@Transactional public Comment 댓글쓰기(String content , int imageId, int userId) { //Tip (객체를 만들 때 id값만 담아서 insert 할 수 있다) Image image = new Image(); image.setId(imageId); User user = new User(); user.setId(userId); Comment comment = new Comment(); comment.setContent(content); comment.setImage(image); comment.setUser(user); return commentRepository.save(comment); }
Java
복사
그러고 댓글쓰기하면
데이터가 성공적으로 온다
근데 댓글에 누가 썼는지 남길려면 user에 username이 필요한데 현재 받아오질못했다
private final UserRepository userRepository; @Transactional public Comment 댓글쓰기(String content , int imageId, int userId) { //Tip (객체를 만들 때 id값만 담아서 insert 할 수 있다) // 대신 return 시에 image객체와 user 객체는 id값만 가지고 있는 빈 객체를 리턴받는다. Image image = new Image(); image.setId(imageId); User userEntity = userRepository.findById(userId).orElseThrow(()->{ throw new CustomApiException("유저 아이디를 찾을 수 없습니다."); }); Comment comment = new Comment(); comment.setContent(content); comment.setImage(image); comment.setUser(userEntity); return commentRepository.save(comment); }
Java
복사
이제 user에 대한 데이터는 다 들고온다

*참고