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

2023. 10. 16. 20:20·Web & Android/스프링 부트 쇼핑몰 프로젝트 with JPA
이 내용은 스프링 부트 쇼핑몰 프로젝트 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;
    }
}

}
```

저작자표시 비영리 변경금지 (새창열림)

'Web & Android > 스프링 부트 쇼핑몰 프로젝트 with JPA' 카테고리의 다른 글

[스프링 부트 쇼핑몰 프로젝트 with JPA] 17-4. 게시판 - Repository  (0) 2023.10.16
[스프링 부트 쇼핑몰 프로젝트 with JPA] 17-2. 게시판 - Controller  (0) 2023.10.16
[스프링 부트 쇼핑몰 프로젝트 with JPA] 17-1. 게시판 - Entity  (1) 2023.10.16
[스프링 부트 쇼핑몰 프로젝트 with JPA] 16.장바구니 상품 삭제 & 주문  (0) 2023.10.16
[스프링 부트 쇼핑몰 프로젝트 with JPA] 15. 장바구니 조회  (1) 2023.10.16
'Web & Android/스프링 부트 쇼핑몰 프로젝트 with JPA' 카테고리의 다른 글
  • [스프링 부트 쇼핑몰 프로젝트 with JPA] 17-4. 게시판 - Repository
  • [스프링 부트 쇼핑몰 프로젝트 with JPA] 17-2. 게시판 - Controller
  • [스프링 부트 쇼핑몰 프로젝트 with JPA] 17-1. 게시판 - Entity
  • [스프링 부트 쇼핑몰 프로젝트 with JPA] 16.장바구니 상품 삭제 & 주문
woojin._.
woojin._.
여러가지 개발을 해보며 발생하는 이야기들에 대한 블로그입니다:)
  • woojin._.
    Jin's Dev Story
    woojin._.
  • 전체
    오늘
    어제
    • 분류 전체보기 (829)
      • Tools (25)
        • eGovFrame (3)
        • GeoServer (3)
        • QGIS (2)
        • LabelImg (2)
        • Git (6)
        • GitHub (1)
        • Eclipse (7)
        • Visual Studio (1)
      • Web & Android (121)
        • SpringBoot (37)
        • Three.js (2)
        • Spring Data JPA (9)
        • 스프링 부트 쇼핑몰 프로젝트 with JPA (25)
        • Thymeleaf (4)
        • Spring Security (15)
        • Flutter (29)
      • Programming Language (61)
        • JAVA (27)
        • JavaScript (14)
        • Dart (2)
        • Python (15)
        • PHP (3)
      • Database (43)
        • PostgreSQL (32)
        • MYSQL (7)
        • Oracle (3)
        • MSSQL (1)
      • SERVER (17)
        • TCP_IP (3)
        • 리눅스 (7)
        • AWS (7)
      • Coding Test (445)
        • 백준[JAVA] (108)
        • 프로그래머스[JAVA] (260)
        • 알고리즘 고득점 Kit[JAVA] (3)
        • SQL 고득점 Kit[ORACLE] (74)
      • CS 지식 (49)
        • [자료구조] (14)
        • [네트워크] (12)
        • [데이터베이스] (10)
        • [알고리즘] (9)
        • [운영체제] (4)
      • 기타 (6)
      • 자격증 & 공부 (62)
        • 정보처리기사 (2)
        • SQLD (6)
        • 네트워크관리사 2급 (5)
        • 리눅스마스터 1급 (44)
        • 리눅스마스터 2급 (1)
        • ISTQB (3)
        • 시스템보안 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 인기 글

  • 태그

    postgresql
    스프링부트
    pcce 기출문제
    Java
    baekjoon
    리눅스마스터
    CS
    리눅스
    스프링 부트 쇼핑몰 프로젝트 with JPA
    python
    JPA
    프로그래머스
    Oracle
    DB
    스프링
    Spring Security
    backjoon
    CS지식
    Linux
    자바
    programmers
    리눅스마스터 1급
    데이터
    플러터
    시큐리티
    데이터베이스
    spring
    백준
    Flutter
    springboot
  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
woojin._.
[스프링 부트 쇼핑몰 프로젝트 with JPA] 17-3. 게시판 - Service
상단으로

티스토리툴바