설명에서 생략된 건 깃허브에!
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "board_id")
private Board board;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member;
private String content;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createdDate;
private String writerNickname;
}
@JsonFormat
을써도 날짜가 제대로 커스텀되지않는 문제가있음. 나중에 수정할것.public class CommentController {
@Autowired
private BoardService boardService;
@PostMapping("/board/comment/{id}")
public String addComment(@PathVariable("id") Long boardId, @RequestParam("content") String content, Authentication authentication) {
CustomUser customUser = (CustomUser) authentication.getPrincipal();
System.out.println("아이디 확인 " + customUser.getId());
boardService.saveComment(customUser.getId(), boardId, content);
return "redirect:/board/view/" + boardId;
}
@PostMapping("/board/view/{boardId}/comment/delete/{commentId}")
public String deleteComment(@PathVariable Long boardId, @PathVariable Long commentId){
boardService.deleteComment(commentId);
return "redirect:/board/view/" + boardId;
}
}
//댓글 가져오기
public List<Comment> getCommentList(Long boardId) {
//boardId로 찾은거 optionalBoard에 저장
Optional<Board> optionalBoard = boardRepository.findById(boardId);
if (optionalBoard.isPresent()) {
//있으면 board에 get함
Board board = optionalBoard.get();
return commentRepository.findByBoardOrderByCreatedDateDesc(board);
}
return Collections.emptyList();
}
//댓글 작성
public void saveComment(Long memberId, Long boardId, String content){
Member member = userRepository.findById(memberId)
.orElseThrow(()-> new IllegalArgumentException("해당 맴버가 없습니다."));
Board board = boardRepository.findById(boardId)
.orElseThrow(()-> new IllegalArgumentException("해당 게시글이 없습니다."));
Comment comment = new Comment();
comment.setContent(content);
comment.setBoard(board);
comment.setMember(member);
comment.setCreatedDate(LocalDateTime.now());
comment.setWriterNickname(member.getNickname());
commentRepository.save(comment);
}
//댓글 삭제
public void deleteComment(Long commentId) {
Comment comment = commentRepository.findById(commentId)
.orElseThrow(()-> new IllegalArgumentException("해당 댓글이 없습니다."));
commentRepository.deleteById(commentId);
}
public void deleteBoard(Long boardId){
...
//게시판의 댓글도 삭제되도록 추가
commentRepository.deleteByBoardId(boardId);
boardLikeRepository.deleteByBoardId(boardId);
boardRepository.deleteById(boardId);
}
비동기로 댓글 수정까지 구현해보려고 했는데 프론트 실력이 부족해서 하지못했다 😅 어렵네;; 그래도 이제 기본적인 게시판이 만들어진것같다. 다음은 출사지 신청인데 게시판과 차별점을 두기위해서 고민해봐야겠다. 동선을 정할수있게 해야하나? 여튼 오늘도 프로젝트 완료! (오프완)