-
스프링 데이터 Common - Web (스프링 데이터 JPA - 6)Programming/Spring Data JPA 2021. 1. 1. 15:47728x90
1. 스프링 Converter
- PostController.java
@RestController public class PostController { @Autowired PostRepository postRepository; @GetMapping("/posts/{id}") public String getPost(@PathVariable Long id) { Optional<Post> byId = postRepository.findById(id); Post post = byId.get(); return post.getTitle(); } }
@RestController public class PostController { @GetMapping("/posts/{id}") public Post getPost(@PathVariable("id") Post post) { return post; } }
2. Pageable, Sort 매개변수
- PostController.java
@RestController public class PostController { @Autowired PostRepository postRepository; @GetMapping("/posts") public Page<Post> getPosts(Pageable pageable) { return postRepository.findAll(pageable); } }
- test
@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc class PostControllerTest { @Autowired MockMvc mockMvc; @Autowired PostRepository postRepository; @Test public void getPost() throws Exception { Post post = new Post(); post.setTitle("hongchan"); postRepository.save(post); mockMvc.perform(get("/posts/" + post.getId())) .andDo(print()) .andExpect(status().isOk()); } @Test public void getPosts() throws Exception { Post post = new Post(); post.setTitle("hongchan"); postRepository.save(post); mockMvc.perform(get("/posts/") .param("page", "0") .param("size", "10") .param("sort", "created,desc") .param("sort", "title")) .andDo(print()) .andExpect(status().isOk()); } }
3. HATEOAS
리소스와 관련된 링크를 함께 제공
1) 의존성 추가
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-hateoas</artifactId> </dependency>
2) 핸들러 매개변수로 PagedResourcesAssembler 추가
@RestController public class PostController { @Autowired PostRepository postRepository; @GetMapping("/posts") public PagedModel<EntityModel<Post>> getPosts(Pageable pageable, PagedResourcesAssembler<Post> assembler) { return assembler.toModel(postRepository.findAll(pageable)); } }
728x90'Programming > Spring Data JPA' 카테고리의 다른 글
스프링 JPA (스프링 데이터 JPA - 7) (0) 2021.01.01 스프링 데이터 Common - 2 (스프링 데이터 JPA - 5) (0) 2021.01.01 스프링 데이터 Common - 1 (스프링 데이터 JPA - 4) (0) 2021.01.01 JPA 프로그래밍 - 2 (스프링 데이터 JPA - 3) (0) 2021.01.01 JPA 프로그래밍 - 1 (스프링 데이터 JPA - 2) (0) 2020.04.30