본문 바로가기

Spring Boot/Spring Boot

44 : Springboot(글 읽기 비즈니스 로직 추가)

글 읽기 비즈니스 로직 추가

  • 기존 코드에서 isDel = "Y" 이면 아래 json response가 나오도록 수정

 

 

 

40: Springboot (Read-board)

Read Board 에 글 읽기 기능을 수행하는 코드를 추가한다 요청 URL은 GET http://localhost:8080/board/{id} 으로 지정 Controller 코드이다. boardService의 getBoardById 로 URL에서 받은 변수 id를 넘겨준다 @G..

dwc04112.tistory.com

 


BoardService

    public ApiResponse<BoardDTO> getBoardById(int boardId) {
        BoardDTO data = boardDAO.getBoardById(boardId);
        if(isDeletedData(data)){
            return new ApiResponse(false, "boardId " + boardId + " is already deleted");
        }
        List<CommentDTO> commentsById = commentDAO.getCommentsByBoardId(boardId);
        data.setComments(commentsById);
        return new ApiResponse(true, data);
    }

    private boolean isDeletedData(BoardDTO data) {
        return data.getIsDel().equals("Y");
    }

아래 논리형 isDeletedData는 data 즉 URL에서 입력한 id에 해당하는 data를 가지고 IsDel이 "Y" 이면 리턴한다   

if문에서 리턴이 오면 false에 해당하는 문구를 출력하고 

if문에서 걸리지 않으면 다음 코드를 실행해서 id에 해당하는 board테이블 데이터와 comment를 보여준다.

 

아래 코드는 commentDAO의 getCommentsByBoardId

@Repository
public interface CommentDAO {

    int postComment(CommentDTO commentDTO);

    List<CommentDTO> getCommentsByBoardId(int boardId);
}

 

 


MyBoardSerivce

    public ApiResponse<BoardDTO> getBoardById(int id) {
        BoardDTO data = boardDAO.getBoardById(id);
        List<CommentDTO> cData = boardDAO.getBoardComment(id);
        String isDel1 = boardDAO.getBoardByIdOri(id).getIsDel();
        if(isDel1.equals("Y")){
            return new ApiResponse(false,"board id "+ id +" is already deleted");
        }else {
            // data.setComments(cData);  --전체 BoardData를 들고옴
            LinkedHashMap<String,Object> member = new LinkedHashMap<>();
            member.put("id",data.getId());
            member.put("author",data.getAuthor());
            member.put("subject",data.getSubject());
            member.put("content",data.getContent());
            member.put("comments",cData);

            return new ApiResponse(true, member);
            //return new ApiResponse(true, data); --전체 BoardData를 들고옴
        }
    }

isDel이 Y일때 문구 출력

if문을 통해서 isDel이 "Y"이면 false에 해당하는 문구가 리턴되게 구현했다. 

여기서 isDel을 들고올때 getBoardById를 쓰지않고 getBoardByIdOri를 하나 더 만들어서

사용한 이유는 6번을 수행하면서 getBoardById는 isDel = "N" 인 값만 보여주게 설정해서.

 

 

board데이터와 commentList 출력

나는 boardDAO에서 List<CommentDTO> getBoardComment(int id); 를 가져왔고

> commentDAO에서 들고오는게 덜 헷갈리고 좋을 것 같다.

LinkedHashMap을 사용하여 board에서는 보여주고싶은 컬럼만 출력되게 했다.