@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonNaming(value = PropertyNamingStrategies.SnakeCaseStrategy.class)
public class BoardDto {
private Long id;
private String userName;
private String title;
private String content;
private LocalDateTime boardAt;
private String status;
private List<CommentDto> commentList = List.of();
}
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonNaming(value = PropertyNamingStrategies.SnakeCaseStrategy.class)
public class CommentDto {
private Long id;
private Long boardId;
private String userName;
private String content;
private LocalDateTime commentAt;
private String status;
}
@Service
public class CommentConverter {
public CommentDto toDto(CommentEntity commentEntity){
return CommentDto.builder()
.id(commentEntity.getId())
.boardId(commentEntity.getBoardEntity().getId())
.userName(commentEntity.getUserName())
.content(commentEntity.getContent())
.status(commentEntity.getStatus())
.commentAt(commentEntity.getCommentAt())
.build()
;
}
}
@Service
@RequiredArgsConstructor
public class BoardConverter {
private final CommentConverter commentConverter;
public BoardDto toDto(BoardEntity boardEntity){
var commentList = boardEntity.getCommentList()
.stream()
.map(commentEntity -> commentConverter.toDto(commentEntity))
.collect(Collectors.toList());
return BoardDto.builder()
.id(boardEntity.getId())
.userName(boardEntity.getUserName())
.title(boardEntity.getTitle())
.content(boardEntity.getContent())
.status(boardEntity.getStatus())
.boardAt(boardEntity.getBoardAt())
.commentList(commentList)
.build()
;
}
}
public List<CommentDto> all(){
// 모든 댓글 엔터티를 조회
List<CommentEntity> commentEntities = commentRepository.findAll();
// 각 댓글 엔터티를 CommentDto로 변환하여 리스트에 추가
return commentEntities.stream()
.map(commentConverter::toDto)
.collect(Collectors.toList());
}
public List<BoardDto> all(){
List<BoardEntity> boardEntities = boardRepository.findAll();
return boardEntities.stream()
.map(boardConverter::toDto)
.collect(Collectors.toList());
}
controller는 생략

delete부분은 게시판 부분만 작성을 해보도록 하겠습니다.
@OneToMany(mappedBy = "boardEntity", cascade = CascadeType.REMOVE, orphanRemoval = true)
cascade = CascadeType.REMOVE, orphanRemoval = true 이 설정들의 기능은 부모가 삭제되면 자식도 함께 삭제된다는 설정과 부모, 자식간의 관계가 끊어지면 자식이 삭제되는 설정. delete를 구현하기 전에 같이 해줘야
게시물이 삭제가 될때 댓글도 같이 삭제된다.
public void delete(Long id){
// board id 찾기
BoardEntity boardDelete = boardRepository.findById(id)
.orElseThrow(() -> new RuntimeException("게시판이 없어: " + id));
boardRepository.delete(boardDelete);
}
@DeleteMapping("/delete/{id}")
public void delete(
@PathVariable Long id){
boardService.delete(id);
}

