TIL 23.01.02

쓰옹·2023년 1월 2일
0

개발자를 향해~~TIL✍

목록 보기
55/87

TODAY


  • 알고리즘 문제풀이
  • 기존 개인과제 blog 변수명 리팩토링 후 팀프로젝트 기본으로 깃에 업로드했어
  • 좋아요 기능 구현


알고리즘 문제풀이


문풀깃허브링크



좋아요 기능


에러

  1. 게시글 좋아요 기능을 만들고 처음으로 포스트맨을 돌려보는데...
// postman
{
    "timestamp": "2023-01-02T07:20:17.592+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "trace": "org.springframework.web.bind.MissingPathVariableException: Required URI template variable 'id' for method parameter type Long is not present\n\tat org.springframework.web.servlet.mvc.method.annotation.PathVariableMethodArgumentResolver.handleMissingValue(PathVariableMethodArgumentResolver.java:101)\n\tat ...",
    "message": "Required path variable 'id' is not present.",
    "path": "/api/posts/1"
}
2023-01-02T16:20:17.590+09:00 WARN 9232 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingPathVariableException: Required URI template variable 'id' for method parameter type Long is not present]
  • 원인

    URI template variable 'id' for method parameter type Long is not present

@PutMapping("/posts/{postId}")
public PostResponseDto updatePost(
						@PathVariable Long id, 
						@RequestBody HttpServletRequest request) { ... }

mapping 시에 적은 url에는 {postId}로 했는데 파라미터에는 id라고 해서 길을 잃었다 빠람빠 빠람빠 ♬


  1. 좋아요 기능 실행 후 상태메세지는 잘 나왔는데 데이터베이스에 저장이 안됨
PostLike postLike = new PostLike(requestedUsername, post);

당연하지 db에 저장을 안했으니까 이 빡대가리야 으휴

PostLike postLike = postLikeRepository.save(new PostLike(requestedUsername*, post));

  1. 이제 좋아요는 되는데 취소가 안됨ㅎ
{
    "timestamp": "2023-01-02T07:52:32.522+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "trace": "java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class com.sparta.blog.entity.PostLike (java.util.ArrayList is in module java.base of loader 'bootstrap'; com.sparta.blog.entity.PostLike is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @71c782bd)\n\tat ...",
    "message": "class java.util.ArrayList cannot be cast to class com.sparta.blog.entity.PostLike (java.util.ArrayList is in module java.base of loader 'bootstrap'; com.sparta.blog.entity.PostLike is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @71c782bd)",
    "path": "/api/posts/1"
}
2023-01-02T16:52:32.507+09:00 ERROR 9364 --- [nio-8080-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class com.sparta.blog.entity.PostLike (java.util.ArrayList is in module java.base of loader 'bootstrap'; com.sparta.blog.entity.PostLike is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @71c782bd)] with root cause

java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class com.sparta.blog.entity.PostLike (java.util.ArrayList is in module java.base of loader 'bootstrap'; com.sparta.blog.entity.PostLike is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @71c782bd)...

postLikeRepository.delete((PostLike) postLikes); 여기가 문제다
캐스팅이 안돼
postLike의 id는 갖고 오지 않았으니까.. username을 사용하거나 postLike 객체를 사용할 수 있으면 좋을텐데...

  • 시도
    • postLikes.clear();

      • 아님. db에서 먹혀야되는데 소용없다 안먹혀 repository에서 뭘 해야하지 걍 저렇게 한다고 되는게 아니라구
    • 어떻게든 id를 구해 삭제를 하겠다는 마음가짐…

      PostLike postLike = null;  // 근데 여기서부터 틀려먹음
              if (postLikes.isEmpty()) {
                  postLike = new PostLike(requestedUsername, post);
                  postLikeRepository.save(postLike);
                  return new ResponseEntity<>("해당 게시글에 좋아요를 했습니다.", HttpStatus.OK);
              } else { // postLike가 있는 상탠데 왜 널이야 어이없어
                  postLikeRepository.deleteById(postLike.getId());
      
      // 예 결과는 널포인터익셉션이다
    • 두둥

      else {
              postLikeRepository.deleteByUsername(requestedUsername);
              return new ResponseEntity<>("좋아요를 취소하였습니다.", HttpStatus.OK);
            }

      List<PostLike> deleteByUsername(String username);

      레파지토리에서 메서드 만들어서 했음 후훟ㅎ훟ㅎ후

      참고 > https://stackoverflow.com/questions/23723025/spring-data-delete-by-is-supported



마무리


오늘부터 해야할 일을 어느정도 계획을 세우고 진행했다. 그리고 시간마다 뭘 했는지 일정에 기록했다. 하루를 돌아보기 참 좋은 것 같다.
좋아요 기능은 다 구현했고 내일 팀원들에게 코드리뷰를 받아야겠다.
그리고 스프링 시큐리티도 적용해보는걸로!

테스트코드도 익혀야하고
오늘 못 들은 후발대 강의도 들어야하고
AOP 공부도 해야한다.

profile
기록하자기록해!

0개의 댓글