기록방

[5일차] 5장 : 게시글 읽기: Read 본문

FrameWork/스프링

[5일차] 5장 : 게시글 읽기: Read

Soom_1n 2024. 3. 29. 13:51

길벗 IT도서에서 주관하는 코딩 자율학습단 8기 : Spring Boot 파트에 참여한 기록입니다 [ 목록 ]

5.1 데이터 조회 과정

  1. 사용자가 데이터를 조회해 달라고 웹 페이지에서 URL 요청을 보냄
  2. 서버의 컨트롤러가 요청을 받아 해당 URL에서 찾으려는 데이터 정보를 리포지토리에 전달
  3. 리포지토리는 정보를 가지고 DB에 데이터 조회 요청
  4. DB는 해당 데이터를 찾아 이를 엔티티로 변환
  5. 반환 된 엔티티는 모델을 통해 뷰 템플릿으로 전달
  6. 최종적으로 결과 뷰 페이지가 완성돼 사용자의 화면에 출력

 

5.2 단일 이터 조회하기

5.2.1 URL 요청받기

  • 게시글 1번 id 조회 : localhost:8080/articles/1
@GetMapping("/articles/{id}") // 데이터 조회 요청 접수 - PathVariable
public String show(@PathVariable Long id) { // 매개 변수로 id 받아오기
    log.info("id = " + id); // id를 잘 받았는지 확인하는 로그 찍기
    return "";
}

http://localhost:8080/articles/1000 결과 잘 출력됨

5.2.2 데이터 조회해 출력하기

    @GetMapping("/articles/{id}") // 데이터 조회 요청 접수 - PathVariable
    public String show(@PathVariable Long id, Model model) { // 매개 변수로 id 받아오기
        log.info("id = " + id); // id를 잘 받았는지 확인하는 로그 찍기
        // 1. id를 조회해 데이터 가져오기
        Article articleEntity = articleRepository.findById(id).orElse(null);
//        Optional<Article> articleEntity = articleRepository.findById(id);

        // 2. 모델에 데이터 등록하기
        model.addAttribute("article", articleEntity);

        // 3. 조회한 데이터를 사용자에게 보여 주기 위한 뷰 페이지 만들고 반환하기
        return "articles/show";
    }
  • findById의 반환값은 옵셔널 객체
  • → 옵셔널로 받거나 orElse()로 없는 경우 처리해주기
{{>layouts/header}}

<table class="table">
    <thead>
    <tr>
        <th scope="col">Id</th>
        <th scope="col">Title</th>
        <th scope="col">Content</th>
    </tr>
    </thead>
    <tbody>
    {{#article}}
    <tr>
        <th>{{id}}</th>
        <td>{{title}}</td>
        <td>{{content}}</td>
    </tr>
    {{/article}}
    </tbody>
</table>

{{>layouts/footer}}
  • mustache에서 변수를 사용하려면 {{#article}} {{/article}} 문법 사용

 

🚀 1분 퀴즈

다음 빈칸에 들어갈 용어를 쓰세요

  • ( @Pathvariable )(이)란 URL 요청으로 들어온 전달값을 컨트롤러의 매개변수로 가져오는 어노테이션입니다.
  • ( findById() )(이)란 JPA의 CurdRepository가 제공하는 메서드로, 특정 엔티티의 id 값을 기준으로 데이터를 찾아 Optional 타입으로 반환합니다.

 

5.3 데이터 목록 조회하기

  • 엔티티가 아니라 엔티티 리스트로 반환받기

5.3.1 URL 요청받기

@GetMapping("/articles")
public String index(Model model) {
    // 1. 모든 데이터 가져오기
    List<Article> articleEntityList = articleRepository.findAll();

    // 2. 모델에 데이터 등록하기
    model.addAttribute("articleList", articleEntityList);

    // 3. 뷰 페이지 설정하기
    return "articles/index";
}
  • CrudRepositry의 findAll() 메서드는 Iterable을 반환함
    • Iterable(interface) ← Collection(interface) ← List(interface) 순으로 상속 구조
  • 반환 타입 불일치 문제 해결 방법
    1. 반환 데이터를 캐스팅(형변환)하기
    2. 반환되는 데이터 형으로 받기
    3. 메서드 반환 데이터 타입을 오버라이딩해서 변경하기
public interface ArticleRepository extends CrudRepository<Article, Long> {
    @Override
    ArrayList<Article> findAll(); // Iterable -> ArrayList 수정
}
  • findAll() 메서드가 ArrayList<> 형으로 반환 됨
{{>layouts/header}}

<table class="table">
    <thead>
    <tr>
        <th scope="col">Id</th>
        <th scope="col">Title</th>
        <th scope="col">Content</th>
    </tr>
    </thead>
    <tbody>
    {{#articleList}}
    <tr>
        <th>{{id}}</th>
        <td>{{title}}</td>
        <td>{{content}}</td>
    </tr>
    {{/articleList}}
    </tbody>
</table>

{{>layouts/footer}}
  • artcleList 로 리스트형 변수가 주어지면, 반복해서 실행 됨

 

🚀 1분 퀴즈

빈칸에 들어갈 용어를 쓰세요.

  • ( findAll() )(이)란 JPA의 CrudRepository가 제공하는 메서드로, 특정 엔티티를 모두 가져와 Iterable 타입으로 변환합니다.

✅ 셀프 체크

MemberController에 회원 조회(특정 회원 조회, 전체 회원 조회) 기능 추가

@GetMapping("/member/{id}")
public String show(@PathVariable Long id, Model model) {
    Member memberEntity = memberRepository.findById(id).orElse(null);
    model.addAttribute("member", memberEntity);

    return "members/show";
}

@GetMapping("/members")
public String index(Model model) {
    List<Member> memberEntityList = memberRepository.findAll();
    model.addAttribute("memberList", memberEntityList);

    return "members/index";
}

🏓 더 알아 볼 내용

1. @PathVariable

  • Path는 URL의 도메인 뒤에 오는 것
  • @PathVariable은 URL에 변수를 지정하는 것
  • 다음은 @PathVariable의 코드
    • name, value, required를 지정할 수 있는데, value와 name은 같은 역할이므로 2가지를 지정할 수 있다고 생각
    • name은 XXMapping에 이름을 지정. 생략하면 @PathVariable 파라미터와 같은 이름
    • required가 true이면 필수 파라미터
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {
	/**
		* Alias for {@link #name}.
		*/
	@AliasFor("name")
	String value() default "";
	/**
	* The name of the path variable to bind to.
		* @since 4.3.3
		*/
	@AliasFor("value")
	String name() default "";
	/**
		* Whether the path variable is required.
		* <p>Defaults to {@code true}, leading to an exception being thrown if the path
		* variable is missing in the incoming request. Switch this to {@code false} if
		* you prefer a {@code null} or Java 8 {@code java.util.Optional} in this case.
		* e.g. on a {@code ModelAttribute} method which serves for different requests.
		* @since 4.3.3
		*/
	boolean required() default true;
}

 

2. CrudRepository

  • 스프링 데이터(Spring Data)에서 제공하는 기능으로 DB와 통신하는 코드 제공
  • Create, Read, Update, Delete의 기본적인 기능을 제공하는 리포지터리
  • CrudRepository는 인터페이스지만, Spring Data JPA 안에 구현체가 있어서 동작할 수있음
    • SimpleJpaRepository.java
  • 이 외에도 CrudRepository의 메소드는 Hibernate의 EntityManager도 사용
728x90