-
[내일배움캠프] 1월 20일 금요일 TIL 회고록카테고리 없음 2023. 1. 20. 21:26
어제 고치지 못했던 페이징 처리 부분을 수정했다. 혼자 하기엔 힘들어서 팀원분한테 물어봐서 겨우겨우 했다 ㅋㅋㅋ
먼저 엔티티 부분을 수정했다.
원래 내가 만든 엔티티에서 사용하지 않고 다른 엔티티에 있는 것을 불러와서 사용했는데 이번에는 내가 만든 엔티티에서 사용을 하게 만들었다.
@Column(nullable = false) public int helpCnt; @Column(nullable = false) public String userImg;
그리고 User와 MatchBoardRequestDto 를 받는 MatchBoard 메소드를 만들었다.
여기서 helpCnt 와 userImg는 user에서 받아오도록 만들었다.
public MatchBoard(User user, MatchBoardRequestDto requestDto) { this.username = user.getUsername(); this.content = requestDto.getContent(); this.helpCnt = user.getHelpCnt(); this.userImg = user.getUserImage(); }
그리고 ResponseDto에 @build 어노테이션을 사용하여 toMatchBoardResponseDto 메소드를 만들었다.
public static MatchBoardResponseDto toMatchBoardResponseDto(final MatchBoard matchBoard) { return MatchBoardResponseDto.builder() .id(matchBoard.getId()) .username(matchBoard.getUsername()) .content(matchBoard.getContent()) .createdAt(matchBoard.getCreatedAt()) .modifiedAt(matchBoard.getModifiedAt()) .status(matchBoard.getStatus()) .boardId(matchBoard.getId()) .helpCnt(matchBoard.getHelpCnt()) .userImg(matchBoard.getUserImg()) .build(); }
Service
팀원분들한테 도움을 받으면서 겨우 만들었다.
// MatchBoard 조회 (페이징 처리) @Override @Transactional public Page<MatchBoardResponseDto> getAllMatchBoard(int page, int size) { // 페이징 처리 Sort sort = Sort.by(Sort.Direction.DESC, "id"); Pageable pageable = PageRequest.of(page,size,sort); Page<MatchBoard> matchBoards = matchBoardRepository.findAll(pageable); Page<MatchBoardResponseDto> matchBoardListDto = matchBoards.map(MatchBoardResponseDto::toMatchBoardResponseDto); return matchBoardListDto; }
문제가 있었다 : MatchBoard에서 게시글을 생성할때 유저별로 한 번만 쓸수 있어야 하지만 한명이 여러번 게시글을 만들 수 있었다.
시도 해 봤다 :
이렇게 User를 받는 Optional을 만들어서 유저를 찾은 다음에, if문을 사용해 isPresent()나 isEmpty를 사용해서 중복을 제거 하려 했지만 안됬다.
Optional<User> user1 = userRepository.findByUsername(userDetails.getUsername());
또, MatchBoardRepository에 findMatchBoardBy() 메서드를 만들고,
Optional<MatchBoard> findMatchBoardBy();
Service 에서 위에 User와 마찬가지로 여러가지 구현을 해봤는데 전부 안됐다..
해결했다 : 팀원분들한테 도움을 받아 해결했다. 먼저 MatchBoardRepository에서 메서드를 만들었다,
Optional<MatchBoard> findByUsername(String username);
그 후 Service에서 기능 구현을 했다.
먼저 user에 getRole이 CUSTOMER 이면 권한이 없다는 익셉션을 출력하게 만들었다.
MatchBoard는 권한이 helper이거나 admin만 작성이 가능하다.
if (user.getRole().equals(UserRoleEnum.CUSTOMER)) { throw new UserException.AuthorityException();
그 후 matchBoardRepository에서 findByUsername으로 user,getUsername().isPresent()를 받아와서
matchBoardRepository에 해당 유저가 이미 들어 가 있다면 이미 게시글을 작성했다는 익셉션을 출력하게 만들었다.
} else if (matchBoardRepository.findByUsername(user.getUsername()).isPresent()) { throw new MatchException.AlreadyMatchBoardFoundExcption();
if문 두개를 통과하면 헬퍼 및 어드민 권한이고, 게시글을 아직 작성하지 않았다는 뜻이므로 게시물을 생성한다.
} else { MatchBoard matchBoard = new MatchBoard(user,requestDto); matchBoardRepository.save(matchBoard); return new MatchBoardResponseDto(matchBoard,board); }
알게된 점 : 앞으로 게시글 제한을 걸어야 할때 이렇게 하면 쉽게 풀 수 있다는 것을 알게되었다.