springframework/Spring Data JPA

Spring Data Common : Web - HATEOAS

Jungsoomin :) 2020. 11. 17. 23:01

PagePagedModel 로 변환

  • PagedModel <EntityModel<Domain>> 형태의 리턴 값을 가지게 된다.
  • 매개변수에 PagedResourcesAssembler<Domain> 추가 가능
  • PagedResourcesAssembler 의 toModel(Page<T>) 메서드로 결과 값을 매핑하여 보낼 수 있음
@GetMapping("/posthateoas")
    public PagedModel<EntityModel<Post>> getPostWithHATEOAS(Pageable pageable, PagedResourcesAssembler<Post> pagedResourcesAssembler){
        Page<Post> all = postRepository.findAll(pageable);
        return pagedResourcesAssembler.toModel(all);
    }
@Test
    public void testHATEOAS() throws Exception {

        for(int i=0; i<20; i++){
            Post post = new Post();
            post.setTitle("JPA" + i);
            postRepository.save(post);
        }

        mockMvc.perform(MockMvcRequestBuilders.get("/posthateoas")
                    .param("page", "1")
                    .param("size","10")
                    .param("sort", "created,desc")
                    .param("sort", "title"))

                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print());
    }

요런 관련링크 들을 띄워주는 것이 HATEOAS 이다.

Body = {
"_embedded":{
	"postList":[{"id":19,"title":"JPA18","created":null},
    			{"id":20,"title":"JPA19","created":null},
                {"id":3,"title":"JPA2","created":null},
                {"id":4,"title":"JPA3","created":null},
                {"id":5,"title":"JPA4","created":null},
                {"id":6,"title":"JPA5","created":null},
                {"id":7,"title":"JPA6","created":null},
                {"id":8,"title":"JPA7","created":null},
                {"id":9,"title":"JPA8","created":null},
                {"id":10,"title":"JPA9","created":null}
                ]},
     // 페이지 네이션 링크 정보 
     "_links":{
     		"first":{"href":"http://localhost/posthateoas?page=0&size=10&sort=created,desc&sort=title,asc"},
            "prev":{"href":"http://localhost/posthateoas?page=0&size=10&sort=created,desc&sort=title,asc"},
            "self":{"href":"http://localhost/posthateoas?page=1&size=10&sort=created,desc&sort=title,asc"},
            "last":{"href":"http://localhost/posthateoas?page=1&size=10&sort=created,desc&sort=title,asc"}
            },
     "page":{"size":10,"totalElements":20,"totalPages":2,"number":1}}