Jin's Dev Story

[스프링 부트 쇼핑몰 프로젝트 with JPA] 17-3. 게시판 - Service 본문

Web & Android/스프링 부트 쇼핑몰 프로젝트 with JPA

[스프링 부트 쇼핑몰 프로젝트 with JPA] 17-3. 게시판 - Service

woojin._. 2023. 10. 16. 20:20
이 내용은 스프링 부트 쇼핑몰 프로젝트 with JPA 책을 학습한 내용입니다.

Service

  • BoardService

      import com.example.walkingmate_back.board.dto.*;
      import com.example.walkingmate_back.board.entity.Board;
      import com.example.walkingmate_back.board.entity.BoardComment;
      import com.example.walkingmate_back.board.repository.BoardRepository;
      import com.example.walkingmate_back.user.entity.UserEntity;
      import com.example.walkingmate_back.user.repository.UserRepository;
      import lombok.RequiredArgsConstructor;
      import org.springframework.data.domain.PageRequest;
      import org.springframework.data.domain.Pageable;
      import org.springframework.data.domain.Sort;
      import org.springframework.stereotype.Service;
      import org.springframework.transaction.annotation.Transactional;
      import java.util.ArrayList;
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
    
      /**
       *    게시글 등록, 수정, 삭제, 단일 조회, 전체 조회
       *    - 서비스 로직
       *
       *   @version          1.00 / 2023.08.07
       *   @author           전우진
       */
    
      @Service
      @RequiredArgsConstructor
      @Transactional
      public class BoardService {
    
          private final BoardRepository boardRepository;
          private final UserRepository userRepository;
    
          /**
           * 사용자 확인 후 게시글 저장
           * - 전우진 2023.07.10
           */
          public BoardResponseDTO saveBoard(BoardRequestDTO boardRequestDTO, String userId) {
              UserEntity user = userRepository.findById(userId).orElse(null);
    
              if(user != null) { // 사용자가 존재하는 경우
                  Board board = new Board(user, boardRequestDTO.getTitle(), boardRequestDTO.getContent());
                  boardRepository.save(board);
    
                  return BoardResponseDTO.builder()
                          .id(board.getId())
                          .userId(board.getUser().getId())
                          .title(board.getTitle())
                          .content(board.getContent())
                          .regTime(board.getRegTime())
                          .updateTime(board.getUpdateTime())
                          .recommend(board.getRecommend())
                          .build();
              } else {
                  // 사용자가 존재하지 않는 경우
                  return null;
              }
          }
    
          /**
           * 게시글 탐색 후 게시글 수정
           * - 전우진 2023.07.10
           */
          public BoardResponseDTO updateBoard(Board board, BoardUpdateDTO boardUpdateDTO, String userId) {
    
              if(userId.equals(board.getUser().getId())) {
                  board.update(boardUpdateDTO);
                  boardRepository.save(board);
    
                  return BoardResponseDTO.builder()
                          .id(board.getId())
                          .userId(board.getUser().getId())
                          .title(board.getTitle())
                          .content(board.getContent())
                          .regTime(board.getRegTime())
                          .updateTime(board.getUpdateTime())
                          .recommend(board.getRecommend())
                          .build();
              }
              return null;
          }
    
          /**
           * 게시글 탐색 후 게시글 삭제
           * - 전우진 2023.07.10
           */
          public BoardResponseDTO deleteBoard(Board board, String userId) {
              if(userId.equals(board.getUser().getId())) {
                  boardRepository.delete(board);
    
                  return BoardResponseDTO.builder()
                          .id(board.getId())
                          .userId(board.getUser().getId())
                          .title(board.getTitle())
                          .content(board.getContent())
                          .regTime(board.getRegTime())
                          .updateTime(board.getUpdateTime())
                          .recommend(board.getRecommend())
                          .build();
              }
              return null;
          }
    
          /**
           * 단일 게시글 조회, 댓글 리턴
           * - 전우진 2023.07.11
           */
          public BoardResponseDTO getBoard(Long id, String userId) {
              Board board = boardRepository.findById(id).orElse(null);
    
              if(board != null) { // 게시글이 존재하는 경우
                  // 댓글
                  List<BoardComment> comments = board.getComments();
    
                  List<BoardCommentResponseDTO> commentDTOList = new ArrayList<>();
                  Map<Long, BoardCommentResponseDTO> commentDTOHashMap = new HashMap<>();
    
                  comments.forEach( c -> {
                      BoardCommentResponseDTO boardCommentResponseDTO = new BoardCommentResponseDTO(c.getId(), c.getBoard().getId(), c.getUser().getId(), c.getContent(), c.getParent() == null ? 0 : c.getParent().getId(), c.getRegTime(), c.getUpdateTime());
                      commentDTOHashMap.put(boardCommentResponseDTO.getId(), boardCommentResponseDTO);
                      if(c.getParent() != null) commentDTOHashMap.get(c.getParent().getId()).getChildren().add(boardCommentResponseDTO);
                      else commentDTOList.add(boardCommentResponseDTO);
                  });
    
                  return BoardResponseDTO.builder()
                          .id(board.getId())
                          .userId(board.getUser().getId())
                          .title(board.getTitle())
                          .content(board.getContent())
                          .regTime(board.getRegTime())
                          .updateTime(board.getUpdateTime())
                          .recommend(board.getRecommend())
                          .isrecommend(board.getRecommends().stream().anyMatch(recommend -> recommend.getUser().getId().equals(userId)))
                          .comments(commentDTOList)
                          .build();
    
              } else {
                  // 게시글이 존재하지 않는 경우
    
                  return null;
              }
          }
    
          /**
           * 게시글 페이징 후 최근 값부터 댓글 포함 리턴
           * - 전우진 2023.07.11
           */
          public List<BoardResponseDTO> getAllBoard(int page, String userId) {
    
              Pageable pageable = PageRequest.of(page - 1, 10, Sort.by("id").descending());
    
              List<Board> boards = boardRepository.findAllBoard(pageable);
              List<BoardResponseDTO> result = new ArrayList<>();
    
              for (Board board : boards) {
                  List<BoardCommentResponseDTO> commentDTOList = new ArrayList<>();
                  Map<Long, BoardCommentResponseDTO> commentDTOHashMap = new HashMap<>();
    
                  board.getComments().forEach( c -> {
                      BoardCommentResponseDTO boardCommentResponseDTO = new BoardCommentResponseDTO(c.getId(), c.getBoard().getId(), c.getUser().getId(), c.getContent(), c.getParent() == null ? 0 : c.getParent().getId(), c.getRegTime(), c.getUpdateTime());
                      commentDTOHashMap.put(boardCommentResponseDTO.getId(), boardCommentResponseDTO);
                      if(c.getParent() != null) commentDTOHashMap.get(c.getParent().getId()).getChildren().add(boardCommentResponseDTO);
                      else commentDTOList.add(boardCommentResponseDTO);
                  });
    
                  BoardResponseDTO boardResponseDTO = new BoardResponseDTO(
                          board.getId(),
                          board.getUser().getId(),
                          board.getTitle(),
                          board.getContent(),
                          board.getRegTime(),
                          board.getUpdateTime(),
                          board.getRecommend(),
                          board.getRecommends().stream().anyMatch(recommend -> recommend.getUser().getId().equals(userId)),
                          commentDTOList
                  );
    
                  result.add(boardResponseDTO);
              }
    
              return result;
          }
    
          public Board FindBoard(Long id){
              return boardRepository.findById(id).orElse(null);
          }
      }
  • BoardCommentService

      import com.example.walkingmate_back.board.dto.*;
      import com.example.walkingmate_back.board.entity.Board;
      import com.example.walkingmate_back.board.entity.BoardComment;
      import com.example.walkingmate_back.board.repository.BoardCommentRepository;
      import com.example.walkingmate_back.board.repository.BoardRepository;
      import com.example.walkingmate_back.user.entity.UserEntity;
      import lombok.RequiredArgsConstructor;
      import org.springframework.stereotype.Service;
      import org.springframework.transaction.annotation.Transactional;
    
      /**
       *    댓글 등록, 수정, 삭제 - 대댓글 포함
       *    - 서비스 로직
       *
       *   @version          1.00 / 2023.08.07
       *   @author           전우진
       */
    
      @Service
      @RequiredArgsConstructor
      @Transactional
      public class BoardCommentService {
          private final BoardCommentRepository boardCommentRepository;
          private final BoardRepository boardRepository;
    
          /**
           * 게시글 & 사용자 확인 후 댓글 저장
           * - 전우진 2023.08.07
           */
          public BoardCommentResponseDTO saveCommemt(BoardCommentRequestDTO boardCommentRequestDTO, UserEntity user, Long boardId) {
    
              Board board = boardRepository.findById(boardId).orElse(null);
              if(board == null) return null; // 게시글이 존재하지 않는 경우
    
              BoardComment boardComment = new BoardComment(user, board, boardCommentRequestDTO.getContent());
    
              BoardComment parentComment;
              Long parentId = 0L;
              if(boardCommentRequestDTO.getParentId() != null) { // 부모 댓글이 있는 경우
                  parentComment = boardCommentRepository.findById(boardCommentRequestDTO.getParentId()).orElse(null);
    
                  boardComment.updateParent(parentComment);
                  parentId = parentComment.getId();
              }
    
              boardCommentRepository.save(boardComment);
    
              return BoardCommentResponseDTO.builder()
                      .id(boardComment.getId())
                      .boardId(boardComment.getBoard().getId())
                      .userId(boardComment.getUser().getId())
                      .content(boardComment.getContent())
                      .regTime(boardComment.getRegTime())
                      .updateTime(boardComment.getUpdateTime())
                      .parentId(parentId)
                      .recommend(boardComment.getRecommend())
                      .build();
          }
    
          /**
           * 게시글 탐색 후 댓글 수정
           * - 전우진 2023.08.07
           */
          public BoardCommentResponseDTO updateComment(BoardComment boardComment, BoardCommentUpdateDTO boardCommentUpdateDTO, String userId) {
              if(userId.equals(boardComment.getUser().getId())) {
                  boardComment.update(boardCommentUpdateDTO);
                  boardCommentRepository.save(boardComment);
    
                  return BoardCommentResponseDTO.builder()
                          .id(boardComment.getId())
                          .boardId(boardComment.getBoard().getId())
                          .userId(boardComment.getUser().getId())
                          .content(boardComment.getContent())
                          .regTime(boardComment.getRegTime())
                          .updateTime(boardComment.getUpdateTime())
                          .recommend(boardComment.getRecommend())
                          .build();
              }
              return null;
          }
    
          /**
           * 게시글 탐색 후 댓글 삭제
           * - 전우진 2023.08.07
           */
          public BoardCommentResponseDTO deleteComment(BoardComment boardComment, String userId) {
    
              if(boardComment.getChildren().size() != 0) { // 자식 있는 경우
                  boardCommentRepository.deleteAllByParentId(boardComment.getId());
                  boardCommentRepository.delete(boardComment);
              } else {
                  boardCommentRepository.delete(boardComment);
              }
              return BoardCommentResponseDTO.builder()
                      .id(boardComment.getId())
                      .boardId(boardComment.getBoard().getId())
                      .userId(boardComment.getUser().getId())
                      .content(boardComment.getContent())
                      .regTime(boardComment.getRegTime())
                      .updateTime(boardComment.getUpdateTime())
                      .recommend(boardComment.getRecommend())
                      .build();
          }
    
          public BoardComment FindBoardComment(Long id){
              return boardCommentRepository.findById(id).orElse(null);
          }
    
      }
  • *RecommendService

    import com.example.walkingmate_back.board.dto.BoardCommentResponseDTO;
    import com.example.walkingmate_back.board.dto.BoardResponseDTO;
    import com.example.walkingmate_back.board.entity.Board;
    import com.example.walkingmate_back.board.entity.BoardComment;
    import com.example.walkingmate_back.board.entity.Recommend;
    import com.example.walkingmate_back.board.entity.RecommendComment;
    import com.example.walkingmate_back.board.repository.BoardCommentRepository;
    import com.example.walkingmate_back.board.repository.BoardRepository;
    import com.example.walkingmate_back.board.repository.RecommendCommentRepository;
    import com.example.walkingmate_back.board.repository.RecommendRepository;
    import com.example.walkingmate_back.user.entity.UserEntity;
    import com.example.walkingmate_back.user.repository.UserRepository;
    import lombok.RequiredArgsConstructor;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    

/**

  • 게시글 좋아요, 댓글 좋아요 저장
    • 서비스 로직
  • @version 1.00 / 2023.08.30
  • @author 전우진
  • /

@Service
@RequiredArgsConstructor
@Transactional
public class RecommendService {

private final RecommendRepository recommendRepository;
private final UserRepository userRepository;
private final BoardRepository boardRepository;
private final BoardCommentRepository boardCommentRepository;
private final RecommendCommentRepository recommendCommentRepository;

/**
 * 좋아요 존재 여부 확인 후 체크
 * - 전우진 2023.08.04
 */
public BoardResponseDTO saveRecommend(Long boardId, String userId) {
    Board board = boardRepository.findById(boardId).orElse(null);
    if(board != null) {
        // 좋아요 존재 여부
        boolean existingRecommend = recommendRepository.existsByBoardIdAndUserId(boardId, userId);

        // 존재하는 경우 - 좋아요 - 1
        if(existingRecommend) {

            if(board != null) {
                board.setRecommend(board.getRecommend() - 1);
            }

            recommendRepository.deleteByBoardIdAndUserId(boardId, userId);

            return BoardResponseDTO.builder()
                    .id(board.getId())
                    .userId(board.getUser().getId())
                    .title(board.getTitle())
                    .content(board.getContent())
                    .recommend(board.getRecommend())
                    .isrecommend(false)
                    .build();
        }

        // 존재하지 않는 경우 - 좋아요 + 1
        UserEntity user = userRepository.findById(userId).orElse(null);

        if(user == null || board == null) {
            return null;
        }

        board.setRecommend(board.getRecommend() + 1);

        Recommend newRecommend = new Recommend(user, board);
        recommendRepository.save(newRecommend);

        return BoardResponseDTO.builder()
                .id(board.getId())
                .userId(board.getUser().getId())
                .title(board.getTitle())
                .content(board.getContent())
                .recommend(board.getRecommend())
                .isrecommend(true)
                .build();
    } else {
        return null;
    }
}

/**
 * 댓글 좋아요 존재 여부 확인 후 체크
 * - 전우진 2023.08.30
 */
public BoardCommentResponseDTO saveRecommendComment(Long commentId, String userId) {
    BoardComment boardComment = boardCommentRepository.findById(commentId).orElse(null);
    if(boardComment != null) {
        // 좋아요 존재 여부
        boolean existingRecommend = recommendCommentRepository.existsByBoardCommentIdAndUserId(commentId, userId);

        // 존재하는 경우 - 좋아요 - 1
        if(existingRecommend) {

            if(boardComment != null) {
                boardComment.setRecommend(boardComment.getRecommend() - 1);
            }

            recommendCommentRepository.deleteByBoardCommentIdAndUserId(commentId, userId);

            return BoardCommentResponseDTO.builder()
                    .id(boardComment.getId())
                    .boardId(boardComment.getBoard().getId())
                    .userId(boardComment.getUser().getId())
                    .content(boardComment.getContent())
                    .regTime(boardComment.getRegTime())
                    .updateTime(boardComment.getUpdateTime())
                    .recommend(boardComment.getRecommend())
                    .isrecommend(false)
                    .build();
        }

        // 존재하지 않는 경우 - 좋아요 + 1
        UserEntity user = userRepository.findById(userId).orElse(null);

        if(user == null || boardComment == null) {
            return null;
        }

        boardComment.setRecommend(boardComment.getRecommend() + 1);

        RecommendComment newRecommend = new RecommendComment(user, boardComment);
        recommendCommentRepository.save(newRecommend);

        return BoardCommentResponseDTO.builder()
                .id(boardComment.getId())
                .boardId(boardComment.getBoard().getId())
                .userId(boardComment.getUser().getId())
                .content(boardComment.getContent())
                .regTime(boardComment.getRegTime())
                .updateTime(boardComment.getUpdateTime())
                .recommend(boardComment.getRecommend())
                .isrecommend(true)
                .build();
    } else {
        return null;
    }
}

}
```