-
[내일배움캠프] 2월 13일 월요일 TIL 회고록카테고리 없음 2023. 2. 13. 21:50
오늘 한 것 : 댓글 작성, 수정, 삭제 POSTMAN으로 테스트, 댓글 전체 조회, 유저별 조회 페이징 처리, 댓글 좋아요 및 좋아요 취소 기능 구현 및 POSTMAN으로 테스트
지난주에 하지 못했던 페이징 처리를 구현했다.
CommentList dto를 만든 후 page, size, isASC 객체를 만들었다.
public class CommentList { private int page; private int size; private boolean isAsc;
그 다음 toPageable 메서드를 만들었다.
page에서 -1을 빼고, Math.max 를 사용해 page 랑 0이랑 비교해 큰 값을 page에 저장한다.
Sort.Direction을 사용해 내림차순으로 정렬하고, "id" 순으로 정렬했다.
public Pageable toPageable() { page -= 1; page = Math.max(page, 0); Sort.Direction direction = isAsc ? Sort.Direction.ASC : Sort.Direction.DESC; // Sort sort = Sort.by(Sort.Direction.DESC, "id"); Sort sort = Sort.by(direction, "id"); return PageRequest.of(page, size, sort); }
그 다음 Service단에서 매개변수로 use와 commentList를 받는 getAllComment 메서드를 만들었다.
commentRepository에 findBy로 commentList.toPageable()를 찾은 뒤 commentPages에 값을 넣는다.
그리고 map을 사용해서 CommentResponse에 값을 넣는다. (아직 이해하지 못했다 ㅠㅠ)
@Override @Transactional(readOnly = true) public Page<CommentResponse> getAllComment(User user, CommentList commentList) { // 페이징 처리 Page<Comment> commentPages = commentRepository.findBy(commentList.toPageable()); return commentPages.map( comment -> new CommentResponse(comment, commentLikeService.addLike((comment.getId())))); }
Map : 지정된 함수에 의해 매핑된 현재 페이지의 내용이 포함된 새 페이지를 반환합니다.
https://minkwon4.tistory.com/131
[JPA] Spring Data JPA (3) - 페이징과 정렬
페이징과 정렬 Spirng Data JPA는 아주 간편한 페이징과 정렬기능을 제공해준다. 메소드의 리턴 타입으로 Page를 사용해주고, pageable이란 파라미터에 시작페이지, 갯수, 정렬조건, 그리고 메소드이름
minkwon4.tistory.com
해당 블로그를 참고하면 더 좋을 것 같다.
팀장님이 댓글같은 경우 Page보다는 슬라이스를 사용하는게 더 나을 것 같다해서 한번 구글링 해봐야겠다.
좋아요도 팀원분이 만든 것을 보며 만들었다.
컨트롤러 단에서 commentId와 userDetails를 매개변수로 받는 changeCommentLike 메서드를 만들었다.
그 다음 commentLikeService에 commentid와 userDetails.get.User(),getId()를 받는 changeCommentLike를 만들었다.
@PostMapping("{commentId}/likes") public void changeCommentLike(@PathVariable Long commentId, @AuthenticationPrincipal UserDetailsImpl userDetails) { commentLikeService.changeCommentLike(commentId, userDetails.getUser().getId()); }
그 다음 if문을 사용해 existsCommentLikeByCommentIdAndUserId를 사용해서 레포지토리에 commentId와 userId가 있으면
findByCommentIdAndUserId를 사용해서 commentId와 userId를 CommentLike commentLike에 넣고
delete 기능을 사용해 레포지토리에서 삭제시킨다.
레포지토리에 commentId와 userId가 없으면 commentLike에 userId,commentId를 새로 넣어준 후 레포지토리에 저장한다.
@Override @Transactional public void changeCommentLike(Long commentId, Long userId) { if (commentLikeRepository.existsCommentLikeByCommentIdAndUserId(commentId, userId)) { CommentLike commentLike = commentLikeRepository.findByCommentIdAndUserId(commentId, userId); commentLikeRepository.delete(commentLike); } else { CommentLike commentLike = new CommentLike(userId, commentId); commentLikeRepository.save(commentLike); } }
좋아요 기능을 만든 후 실행고 POSTMAN에서 테스트 하려고 했더니 오류가 나왔다.
Unable to locate Attribute with the the given name [id] on this ManagedType 오류가 나와서 구글링 해봤더니 소문자 i가 아닌
대문자 i로 id를 적으면 오류가 나온다고 적혀있었다.
그래서 Comment 엔티티와 CommentLike 엔티티 부분에 있는 id 부분을 전부 소문자 i로 바꿔주었다.
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
바꾼 후 실행했더니 오류가 사라졌다.
알게된 점 : 대문자 i말고 소문자 i를 쓰자!
페이징 처리와 좋아요 기능 구현이 너무 힘들었다. 김영한님 강의나 책으로 따로 공부해야 할 것 같다.