TIL

20240905_TIL

Coding-Su 2024. 9. 5. 21:45
728x90

1. 내일배움캠프 Sping 

오늘은 팀 프로젝트를 하였습니다. 프로젝트를 마무리하고 마지막 수정할 부분과 오류들을 수정하고 발표자료를 만들었습니다.

 

 

2. 김영한의 스프링 기본편

세션 9. 빈 생명주기 콜백에 관하여 공부하였습니다.

[Spring] Bean 생명주기 콜백

 

[Spring] Bean 생명주기 콜백

강의스프링 핵심 원리 - 기본편 스프링 핵심 원리 - 기본편 강의 | 김영한 - 인프런김영한 | 스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질

coding-su.tistory.com

 

 

3. 코딩테스트

  1. [프로그래머스] 카펫 JAVA  
  2. [프로그래머스] 주문량이 많은 아이스크림들 조회하기 MySql

 

 

4. 스프링 숙련 프로젝트

오늘은 게시글을 기간별 검색 기능을 추가하였고, 게시글을 삭제할때 좋아요 부분과 댓글, 댓글 좋아요 부분을 모두 삭제해야 함으로 이 부분을 수정하였습니다.

https://github.com/KJG04/sparta-news-feed

 

GitHub - KJG04/sparta-news-feed

Contribute to KJG04/sparta-news-feed development by creating an account on GitHub.

github.com

 

게시글을 기간별 검색 기능


BoardsController

    @GetMapping("/date")
    public ResponseEntity<Page<BoardsResponseDto>> getAllBoardsWithDate(@RequestParam(name = "page", defaultValue = "1") int page,
                                                                        @RequestParam(name = "size", defaultValue = "10") int size,
                                                                        @RequestParam(name = "sortBy",defaultValue = "createAt") String sortBy,
                                                                        @RequestParam(name = "isAsc", defaultValue = "false") boolean isAsc,
                                                                        @RequestParam(name = "startDate", defaultValue = "") String startDate,
                                                                        @RequestParam(name = "endDate", defaultValue = "") String endDate,
                                                                        User user) {
        List<Friend> friendList = friendService.getFriendsByFromUserId(user.getUserId());
        Page<BoardsResponseDto> boardsResponseDtoList = boardsService.getAllBoardsWithDate(page-1, size, sortBy, isAsc, friendList, startDate, endDate ,user);
        return new ResponseEntity<>(boardsResponseDtoList, HttpStatus.OK);
    }

 

 

BoardsService

    public Page<BoardsResponseDto> getAllBoardsWithDate(int page, int size, String sortBy, boolean isAsc, List<Friend> friendList, String startDate, String endDate, User user) {
        // pageing 처리
        Sort.Direction direction = isAsc ? Sort.Direction.ASC : Sort.Direction.DESC;
        Sort sort = Sort.by(direction, sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);

        List<Long> userList = new ArrayList<>();
        // 자신의 글을 불러오기 위해 로그인 한 사람 id 추가
        userList.add(user.getUserId());
        // 친구들의 글을 불러오기 위해 친구 id 추가
        for (Friend friend : friendList) {
            userList.add(friend.getToUser().getUserId());
        }

        // 친구의 글을 가져와서 dto에 넣어줌
        LocalDateTime startDateTime = LocalDateTime.of(Integer.parseInt(startDate.substring(0, 4)), Integer.parseInt(startDate.substring(5, 7)), Integer.parseInt(startDate.substring(8, 10)), 0, 0, 0);
        LocalDateTime endDateTime = LocalDateTime.of(Integer.parseInt(endDate.substring(0, 4)), Integer.parseInt(endDate.substring(5, 7)), Integer.parseInt(endDate.substring(8, 10)), 23, 59, 59);
        System.out.println(startDateTime);
        System.out.println(endDateTime);
        Page<BoardsResponseDto> boardsResponseDtoList = boardsRepository.findAllByUserIdAndDate(pageable, userList, startDateTime, endDateTime).map(BoardsResponseDto::new);

        // 댓글 개수와, 좋아요개수 넣어줌
        for (BoardsResponseDto boardsResponseDto : boardsResponseDtoList) {
            List<BoardsLike> boardsLikeList = boardsLikeRepository.findAllByBoardIdAndLikeState(boardsResponseDto.getBoardId(), true);
            List<Comment> comments = commentRepository.findAllByBoards_BoardId(boardsResponseDto.getBoardId());
            boardsResponseDto.update(boardsLikeList.size(), comments.size());
        }

        return boardsResponseDtoList;
    }

 

BoardsRepository

    @Query("select b from Boards b where b.userId In :userList AND b.createAt BETWEEN :startDate AND :endDate")
    Page<Boards> findAllByUserIdAndDate(Pageable pageable, @Param("userList") List<Long> userList, @Param("startDate") LocalDateTime startDate, @Param("endDate")LocalDateTime endDate);

 

시작하는 날짜와 끝나는 날짜를 입력 받아서 service에서 문자를 LocalDateTime으로 변환해 주고 repository에서 쿼리를 날려서 원하는 데이터를 가져오도록 하였습니다.

 

 

게시글을 삭제할때 좋아요 부분과 댓글, 댓글 좋아요 부분을 모두 삭제

 

BoardsService

    @Transactional
    public Long deleteBoard(Long boardId, User user) {
        // 작성자만 글을 삭제할 수 있습니다.
        Boards boards = getOneBoardWithId(boardId);
        if (boards.getUserId().equals(user.getUserId())) {
            // 해당 게시글의 좋아요 정보 삭제
            List<BoardsLike> boardsLikes = boardsLikeRepository.findAllByBoardId(boards.getBoardId());
            boardsLikeRepository.deleteAll(boardsLikes);

            // 해당 게시글의 댓글 정보 삭제 -> Boards필드의 boardId와 같은 값의 댓글들 정보를 조회
            List<Comment> comments = commentRepository.findAllByBoards_BoardId(boards.getBoardId());
            for(Comment comment : comments) {
                // 관련된 각 댓글에 달린 좋아요 정보 삭제
                List<CommentLike> commentLikes = comment.getLikes();
                // 해당 댓글에 좋아요가 달려있는지 확인
                if(commentLikes != null && !commentLikes.isEmpty()) {
                    commentLikeRepository.deleteAll(commentLikes);
                }
            }
            commentRepository.deleteAll(comments);

            boardsRepository.delete(getOneBoardWithId(boardId));
            return boardId;
        } else {
            throw new ResponseStatusException( HttpStatus.FORBIDDEN, "권한이 없습니다.");
        }
    }

 

연관되어있는 부분을 찾아서 모두 삭제를 해준다음 board를 삭제하였습니다.

728x90

'TIL' 카테고리의 다른 글

20240909_TIL  (0) 2024.09.11
20240906_TIL  (1) 2024.09.08
20240904_TIL  (0) 2024.09.05
20240903_TIL  (0) 2024.09.03
20240902_TIL  (2) 2024.09.03