1. 화면 분석
Board - id, title, content
User - id, username

2. 컨트롤러 작성
URL에 테이블 명 뒤에 들어오는 값은 PK or UK
나머지는 다 queryString

@GetMapping("/board/{id}")
public String detail(@PathVariable int id) {
System.out.println("id : "+id);
return "board/detail";
}

[ @PathVariable ]
@GetMapping("/board/{id}")와 같이 @PathVariable을 사용하여
경로에 {id}라는 변수를 선언한 경우, 해당 부분의 값을 추출하여 메서드의 매개변수로 전달.
예를 들어, "/board/1"이라는 요청이 들어오면, id 매개변수에는 1이 전달된다.
이렇게 추출된 값은 메서드 내부에서 활용할 수 있다.
@PathVariable은 동적인 URL을 다룰 때 유용하게 사용된다.
예를 들어, 게시물의 상세 페이지를 보여주는 URL인 "/board/{id}"에서
{id} 부분을 각각의 게시물 식별자로 대체하여 동적인 경로를 처리할 수 있다.
간단히 말해서, @PathVariable은 URL 경로에서 변수 값을 추출하여 활용하는 기능을 제공
3. 응답 DTO 만들기
package shop.mtcoding.blog.board;
import lombok.Data;
public class BoardResponse {
@Data
public static class DetailDTO {
private int id;
private String title;
private String content;
private int userId;
private String username;
}
}
4. findById() 만들기
public BoardResponse.DetailDTO findById(int idx) {
Query query = em.createNativeQuery("select b.id, b.title, b.content, b.user_id, u.username from board_tb b inner join user_tb u on b.user_id = u.id where b.id = ?");
query.setParameter(1, idx);
Object[] row = (Object[]) query.getSingleResult();
Integer id = (Integer) row[0];
String title = (String) row[1];
String content = (String) row[2];
int userId = (Integer) row[3];
String username = (String) row[4];
System.out.println("id : "+id);
System.out.println("title : "+title);
System.out.println("content : "+content);
System.out.println("userId : "+userId);
System.out.println("username : "+username);
return null;
}
Query query = em.createNativeQuery("select b.id, b.title, b.content, u.user_id, u.username from board_tb b inner join user_tb u on b.user_id = u.id where b.id = ?");
이거... Board.class나 User.class에 담을 수 있나? xxx
Object[] row = (Object[]) query.getSingleResult();
엔티티가 아니라 하나하나의 타입을 모른다. 때문에 Object[] 배열 타입을 리턴
0번지 = id
1번지 = title
2번지 = content
3번지 = userId 이런 식으로 들어간다.
Object 타입이기 때문에 다운 캐스팅해서 넣으면 된다.
이건 쓸 일 없다! 아, 이거 Object[] 배열 타입이구나! 하고 원리만 알고 넘어가자.
5. 테스트 해보기
http://localhost:8080/board/1

6. DTO에 옮기기
public BoardResponse.DetailDTO findById(int idx) {
Query query = em.createNativeQuery("select b.id, b.title, b.content, b.user_id, u.username from board_tb b inner join user_tb u on b.user_id = u.id where b.id = ?");
query.setParameter(1, idx);
Object[] row = (Object[]) query.getSingleResult();
Integer id = (Integer) row[0];
String title = (String) row[1];
String content = (String) row[2];
int userId = (Integer) row[3];
String username = (String) row[4];
System.out.println("id : "+id);
System.out.println("title : "+title);
System.out.println("content : "+content);
System.out.println("userId : "+userId);
System.out.println("username : "+username);
BoardResponse.DetailDTO responseDTO = new BoardResponse.DetailDTO();
responseDTO.setId(id);
responseDTO.setTitle(title);
responseDTO.setContent(content);
responseDTO.setUserId(userId);
responseDTO.setUsername(username);
return responseDTO;
}
지금... User.class, Board.class 이걸 못 써서 이런... 짓을.... 하는 듯 데이터베이스에서 조회한 결과를 파싱(parsing)하여 BoardResponse.DetailDTO 객체에 저장하는 과정을 보여줍니다....

[ 방법2. setter말고 생성자로 담기 ]


7. 가방에 담아서 화면에 전달

8. 화면에서 렌더링


Share article