개발/Spring(Hodol)

Spring - 게시글 조회 (다건 조회, 임시 H2 활용한 실제 서비스 확인)

잇(IT) 2023. 8. 30. 15:21
728x90

- 게시글 여러개를 조회하기 위한 Controller를 작성

 

- PostController.java

.....

@GetMapping("/posts")
    public List<PostResponse> getList() {
        return postService.getList();
    }
}

- 기존의 데이터를 가져오는 것이기 때문에 Post가 아닌 Get을 사용하며, 게시글을 여러개 가져올 것이기 때문에 Post 엔티티를 여러개 가여와야 하지만 원하는 조건에 응답을 하기 위해 PostResponse List로 받아온다.

 

- PostService.java

.....

public List<PostResponse> getList() {
        return postRepository.findAll().stream()
                .map(post -> new PostResponse(post))
                .collect(Collectors.toList());
    }
}

- builder를 통해 PostResponse의 객체의 데이터를 주입할 수 있지만 해당 코드가 반복될 경우 번거로울 수 있다.

- stream을 통해 DB에서 가져온 Post 엔티티들을 PostResponse 객체에 복사한 뒤 List로 반환한다.

 

- PostResponse.java

.....

//생성자 오버로딩
    public PostResponse(Post post) {
        this.id = post.getId();
        this.title = post.getTitle();
        this.content = post.getContent();
    }
    //생성자를 통해 Post 엔티티의 값을 바로 받아오는 생성자를 하나 생성한다.
    
    .....

- 생성자 오버라이딩을 통해 Post 엔티티의 값을 PostResponse 객체에 바 넣는 생성자를 생성한다.

 

- PostServiceTest.java

@Test
    @DisplayName("글 다건 조회")
    void test3() {
        postRepository.saveAll(List.of(
                Post.builder()
                        .title("Title_1")
                        .content("Content_1")
                        .build(),
                Post.builder()
                        .title("Title_2")
                        .content("Content_2")
                        .build()
        ));

        List<PostResponse> postResponses = postService.getList();
        
        assertEquals(2L, postResponses.size());
    }

- saveAll(List.of()) 메서드를 통해 여러개의 객체를 List에 한 번에 저장할 수 있다.

 

- PostControllerTest.java

@Test
    @DisplayName("글 다건 조회")
    void test5() throws Exception {
        //given
        List<Post> posts = postRepository.saveAll(List.of(
                Post.builder()
                        .title("Title_1")
                        .content("Content_1")
                        .build(),
                Post.builder()
                        .title("Title_2")
                        .content("Content_2")
                        .build()
        ));

        //expected
        mockMvc.perform(MockMvcRequestBuilders.get("/posts/")
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(jsonPath("$.length()", Matchers.is(2)))
                .andExpect(jsonPath("$[0].id").value(posts.get(0).getId()))
                .andExpect(jsonPath("$[0].title").value("Title_1"))
                .andExpect(jsonPath("$[0].content").value("Content_1"))
                .andExpect(jsonPath("$[1].id").value(posts.get(1).getId()))
                .andExpect(jsonPath("$[1].title").value("Title_2"))
                .andExpect(jsonPath("$[1].content").value("Content_2"))
                .andDo(MockMvcResultHandlers.print());
    }
}

*

.andExpect(jsonPath("$.length()", Matchers.is(2)))

- 위 코드를 통해 List의 길이를 가져올 수 있다.

 


- 임시 H2 DB 설정 및 사용

 

- application.yaml

spring:
  h2:
    console:
      enabled: true
      path: /h2-console
  #      h2 DB를 임시로 생성하여 사용할 수 있다.
  datasource:
    url: jdbc:h2:mem:islog
    username: sa
    password:
    driver-class-name: org.h2.Driver

 

 

728x90