1. 글 목록조회
- 필요한 정보 : id, title
2.BoardResponse 에 MainDTO 만들기
package shop.mtcoding.blog.board; import lombok.Data; import shop.mtcoding.blog.user.User; public class BoardResponse { @Data public static class MainDTO { private Integer id; private String title; public MainDTO(Board board) { this.id = board.getId(); this.title = board.getTitle(); } } }
3. BoardService 에 findAll() 수정하기
package shop.mtcoding.blog.board; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import shop.mtcoding.blog._core.errors.exception.Exception403; import shop.mtcoding.blog._core.errors.exception.Exception404; import shop.mtcoding.blog.user.User; import java.util.List; @RequiredArgsConstructor @Service public class BoardService { private final BoardJPARepository boardJPARepository; public List<BoardResponse.MainDTO> findAll() { // 글목록조회 Sort sort = Sort.by(Sort.Direction.DESC, "id"); List<Board> boardList = boardJPARepository.findAll(sort); return boardList.stream().map(board -> new BoardResponse.MainDTO(board)).toList(); // return boardList.stream().map(BoardResponse.MainDTO::new).toList();와 같은 것 } }
4. BoardController 에 main 수정하기
package shop.mtcoding.blog.board; import jakarta.servlet.http.HttpSession; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import shop.mtcoding.blog._core.utils.ApiUtil; import shop.mtcoding.blog.user.User; import java.util.List; @RequiredArgsConstructor @RestController public class BoardController { private final HttpSession session; private final BoardService boardService; @GetMapping("/") public ResponseEntity<?> main() { List<BoardResponse.MainDTO> respDTO = boardService.findAll(); return ResponseEntity.ok(respDTO); // board에 연관된 객체가 있기에 위험함 / 무한 참조가 일어날 수 있음 } }
Share article