2024. 12. 9. 21:15ㆍSpring Framework/Spring HATEOAS
📌 EntityModel<T>
란?
Spring HATEOAS에서 제공하는 EntityModel<T>
는 단일 리소스(엔터티)와 하이퍼미디어 링크를 함께 포함할 수 있는 컨테이너 클래스입니다.
🔹 주요 역할
1️⃣ REST API에서 엔터티 데이터를 감싸고 링크를 추가
2️⃣ 하이퍼미디어(HATEOAS) 원칙을 따르는 API를 만들 수 있도록 지원
3️⃣ RepresentationModel<T>
를 상속받으며, 추가적으로 엔터티 데이터를 보관 가능
🎯 EntityModel<T>
의 기본 구조
아래 License
클래스를 기반으로 EntityModel<T>
의 사용법을 알아보겠습니다.
✅ 기본 엔티티 클래스
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class License {
private int id;
private String licenseId;
private String description;
private String organizationId;
private String productName;
private String licenseType;
}
📌 설명
License
는 일반적인 엔티티 또는 DTO 클래스EntityModel<License>
를 사용하여 HATEOAS 링크를 추가 가능
🛠️ EntityModel<T>
활용: 링크 추가하기
1️⃣ LicenseController
에서 EntityModel<T>
반환
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/licenses")
public class LicenseController {
@GetMapping("/{licenseId}")
public EntityModel<License> getLicense(@PathVariable String licenseId) {
License license = new License();
license.setId(1);
license.setLicenseId(licenseId);
license.setDescription("Enterprise License");
license.setOrganizationId("Org123");
license.setProductName("ProductX");
license.setLicenseType("Full");
// 🔗 현재 라이선스의 self 링크 추가
EntityModel<License> entityModel = EntityModel.of(license);
entityModel.add(linkTo(methodOn(LicenseController.class).getLicense(licenseId)).withSelfRel());
return entityModel;
}
}
📌 설명
EntityModel.of(license)
→License
객체를EntityModel<T>
로 감쌈linkTo(methodOn(...))
를 사용하여 현재 리소스에 대한 self 링크 추가entityModel.add(selfLink);
→EntityModel<T>
객체에 링크 추가
📡 실제 API 응답(JSON)
위 getLicense()
메서드를 호출하면 아래와 같은 JSON 응답을 받을 수 있습니다.
{
"id": 1,
"licenseId": "L12345",
"description": "Enterprise License",
"organizationId": "Org123",
"productName": "ProductX",
"licenseType": "Full",
"_links": {
"self": {
"href": "http://localhost:8080/licenses/L12345"
}
}
}
📌 설명
- 기존
License
엔티티의 데이터(id
,licenseId
등)가 유지됨 _links.self.href
→ 현재 리소스에 대한 HATEOAS 링크가 자동 추가됨
🎯 RepresentationModel<T>
vs EntityModel<T>
차이점
클래스 | 역할 | 특징 |
---|---|---|
RepresentationModel<T> |
하이퍼미디어 링크 제공 | 데이터 필드 없음 (링크만 추가 가능) |
EntityModel<T> |
엔티티 + 링크 제공 | 데이터 필드 + 링크 포함 가능 |
📌 비교 예제
✅ RepresentationModel<T>
사용 예제 (링크만 추가)
public class LicenseModel extends RepresentationModel<LicenseModel> { }
📌 JSON 응답 예시
{
"_links": {
"self": {
"href": "http://localhost:8080/licenses/1"
}
}
}
✅ EntityModel<T>
사용 예제 (데이터 + 링크 포함)
EntityModel<License> entityModel = EntityModel.of(license);
entityModel.add(linkTo(methodOn(LicenseController.class).getLicense(licenseId)).withSelfRel());
📌 JSON 응답 예시
{
"id": 1,
"licenseId": "L12345",
"description": "Enterprise License",
"organizationId": "Org123",
"productName": "ProductX",
"licenseType": "Full",
"_links": {
"self": {
"href": "http://localhost:8080/licenses/L12345"
}
}
}
📌 정리
RepresentationModel<T>
→ 단순한 링크만 제공 (데이터 X)EntityModel<T>
→ 엔터티 데이터 + 링크를 함께 포함 가능
🔗 CollectionModel<T>
를 사용하여 리스트 응답 처리
📌 여러 개의 License
객체를 포함하는 응답 만들기
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.Link;
import java.util.List;
public class LicenseModelList extends CollectionModel<License> {
public LicenseModelList(List<License> licenses, Link link) {
super(licenses, link);
}
}
📌 응답 예시 (JSON)
{
"_embedded": {
"licenses": [
{
"id": 1,
"licenseId": "L12345",
"_links": {
"self": {
"href": "http://localhost:8080/licenses/L12345"
}
}
},
{
"id": 2,
"licenseId": "L67890",
"_links": {
"self": {
"href": "http://localhost:8080/licenses/L67890"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/licenses"
}
}
}
📌 설명
_embedded.licenses
→ 여러 개의License
객체를 포함- 각
License
객체는 개별적으로 self 링크 포함 _links.self.href
→ 전체 컬렉션에 대한 컬렉션 링크 포함
📢 Summary
✅ EntityModel<T>
는 하이퍼미디어 링크를 추가하면서 엔터티 데이터를 유지하는 컨테이너
✅ EntityModel.of(T)
를 사용하여 엔터티 객체를 감쌀 수 있음
✅ RepresentationModel<T>
와 달리 데이터 필드와 링크를 동시에 가질 수 있음
✅ CollectionModel<T>
를 활용하면 엔티티 리스트와 링크를 함께 제공 가능
✅ WebMvcLinkBuilder
를 활용하여 동적으로 링크를 추가 가능
이제 EntityModel<T>
를 활용하여 더 직관적이고 RESTful한 API를 만들 수 있습니다! 🚀
'Spring Framework > Spring HATEOAS' 카테고리의 다른 글
HATEOAS(Hypermedia as the Engine of Application State) (0) | 2025.03.03 |
---|---|
WebMvcLinkBuilder (0) | 2024.12.11 |
_links (0) | 2024.12.11 |
self 링크 (0) | 2024.12.09 |
RepresentationModel (0) | 2024.12.09 |