inblog logo
|
devleekangho
    스프링부트

    [스프링 부트] 11. 글 상세 보기(Read) 구현

    KangHo Lee's avatar
    KangHo Lee
    Nov 18, 2024
    [스프링 부트] 11. 글 상세 보기(Read) 구현
    Contents
    1. View2. Controller3. Service4. Repository5. DTO (Data Transfer Object)

    1. View

    <section> <div> 번호 : {{model.id}} <br> 제목 : {{model.title}} <br> 내용 : {{model.content}} <br> 작성일 : {{model.createdAt}} <br> </div> </section>

    2. Controller

    @GetMapping("/board/{id}") public String detail(@PathVariable("id") int id, Model model) { BoardResponse.DetailDTO boardDetail = boardService.게시글상세보기(id); model.addAttribute("model", boardDetail); return "detail"; }
    💡
    @PathVariable 어노테이션은 Spring MVC에서 URL 경로의 일부를 변수로 받아올 때 사용됩니다.

    3. Service

    public BoardResponse.DetailDTO 게시글상세보기(int id) { Board board = boardRepository.findById(id); return new BoardResponse.DetailDTO(board); }

    4. Repository

    public Board findById(int id) { Query q = em.createNativeQuery("select * from board_tb where id = ?", Board.class); q.setParameter(1, id); // Object 반환이라 다운캐스팅 필요 return (Board) q.getSingleResult(); }
    💡
    q.setParameter() 의 매개 변수는 (물음표 순서, 물음표에 바인딩될 변수값)

    5. DTO (Data Transfer Object)

    @Data public static class DetailDTO { private int id; private String title; private String content; private String createdAt; // Timestamp인데 string으로 해도 된다. public DetailDTO(Board board) { this.id = board.getId(); this.title = board.getTitle(); this.content = board.getContent(); // TimeStamp -> String 과정 필요 this.createdAt = DateToForm.dateToFrom(board); } }

    DateToForm.java

    public class DateToForm { // 2024-11-18 10:27:40.425744 -> 2024.11.18 (년, 월, 일)만 출력하도록 변경 public static String dateToFrom (Board board) { Date createdAt = board.getCreatedAt(); // 대문자 MM인 이유 -> 분(minute)랑 겹치지 않게 SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd"); return sdf.format(createdAt); } }
     
    Share article
    Contents
    1. View2. Controller3. Service4. Repository5. DTO (Data Transfer Object)

    devleekangho

    RSS·Powered by Inblog