JPA 심화 2-5

5w31892p·2023년 2월 3일
0

JPA 심화

목록 보기
10/19

HATEOAS

  • Hypermedia As The Engine of Application State
  • 다음 요청을 위한 하이퍼링크가 제공되어야 한다.
  • 클라이언트 화면이 필요 없을 만큼 제공되어야 한다.

:: HATEOAS 적용 예시

  • 게시글 조회 API를 호출했을때
{
  "data": {
    "id": 1000,
    "name": "게시글 1",
    "content": "HAL JSON을 이용한 예시 JSON",
    "self": "http://localhost:8080/api/post/1000", // 호출한 api 주소
    "profile": "http://localhost:8080/docs#query-article", // 호출한 api 문서
    "next": "http://localhost:8080/api/post/1001", // 다음 post를 조회 api 주소
    "comment": "http://localhost:8080/api/post/comment", // post의 댓글 달기 api 주소
    "save": "http://localhost:8080/api/feed/post/1000", // post을 내 피드로 저장 api 주소
  },
}

:: HATEOAS -> SpringData JPA 페이징에 적용

  1. 의존성 추가
// 9. SpringBoot HATEOAS 의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
  1. 핸들러 매개변수로 PagedResourcesAssembler 넣고 PagedModel 로 응답
    -> 이전에는 PagedResource로 응답했지만 PagedModel로 바뀜
@RestController
public class ChannelController {

  @Autowired
  ChannelRepository channelRepository;

  @GetMapping("/channels")
  public PagedModel<User> getUsers(Pageable pageable, PagedResourcesAssembler<User> assembler) {
    var all = channelRepository.findAll(pageable);
    return assembler.toModel(all);
  }

}

:: 결과

  • 적용 전 (기본 pageable)
{  
   "content":[  
...
      {  
         "id":140,
         "title":"jpa"
      }
   ],
   "pageable":{  
      "sort":{  
         "sorted":true,
         "unsorted":false
      },
      "offset":20,
      "pageSize":10,
      "pageNumber":2,
      "unpaged":false,
      "paged":true
   },
   "totalElements":200,
   "totalPages":20,
   "last":false,
   "size":10,
   "number":2,
   "first":false,
   "numberOfElements":10,
   "sort":{  
      "sorted":true,
      "unsorted":false
   }
}
  • 적용 후 (PageModel (PagedResource))
{  
   "_embedded":{  
      "channelList":[  
         {  
            "id":140,
            "title":"jpa"
         },
...
         {  
            "id":109,
            "title":"jpa"
         }
      ]
   },
   "_links":{  
      "first":{  
         "href":"http://localhost/channels?page=0&size=10&sort=created,desc&sort=title,asc"
      },
      "prev":{  
         "href":"http://localhost/channels?page=1&size=10&sort=created,desc&sort=title,asc"
      },
      "self":{  
         "href":"http://localhost/channels?page=2&size=10&sort=created,desc&sort=title,asc"
      },
      "next":{  
         "href":"http://localhost/channels?page=3&size=10&sort=created,desc&sort=title,asc"
      },
      "last":{  
         "href":"http://localhost/channels?page=19&size=10&sort=created,desc&sort=title,asc"
      }
   },
   "page":{  
      "size":10,
      "totalElements":200,
      "totalPages":20,
      "number":2
   }
}

:: JPA 사용 이유

  • JPA로 많이 넘어간 까닭은, 데이터모델이 단순해진 탓
  • 대신 데이터 흐름이 매우 정교 해짐
  • DDD(도메인 주도 개발)이 중심이 되어가고 있기 때문
  • MSA 를위해 도메인 중심으로 모듈이 분리될 수 있는 구조로 프로젝트들이 발전해오고 있음

0개의 댓글