Spring Hateoas, by default, produces JSON containing collection names as classNameList
format. We can customize the name generated for embedded collection model using @Relation
tag.
1. Use @Relation to customize embedded collection name
The org.springframework.hateoas.server.core.Relation
annotation is used to configure the relation to be used when embedding objects in HAL representations of EntityModel
and CollectionModel
.
It has two attributes:
value
oritemRelation
– is used when referring to a single resource.collectionRelation
– is used when referring to a collection of resources.
Example Usage
@Data @Builder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = false) @Relation(collectionRelation = "albums", itemRelation = "album") @JsonInclude(Include.NON_NULL) public class AlbumModel extends RepresentationModel<AlbumModel> { private Long id; private String title; private String description; private String releaseDate; private List<ActorModel> actors; }
2. JSON responses
2.1. Without @Relation annotation
{ "_embedded": { "albumModelList": [ { "id": 1, "title": "Top Hits Vol 1", "description": "Top hits vol 1. description", "releaseDate": "10-03-1981", "actors": [ { "id": 1, "firstName": "John", "lastName": "Doe", "_links": { "self": { "href": "http://localhost:8080/api/actors/1" } } } ], "_links": { "self": { "href": "http://localhost:8080/api/actors/1" } } } ] } }
2.2. With @Relation annotation
{ "_embedded": { "albums": [ { "id": 1, "title": "Top Hits Vol 1", "description": "Top hits vol 1. description", "releaseDate": "10-03-1981", "actors": [ { "id": 1, "firstName": "John", "lastName": "Doe", "_links": { "self": { "href": "http://localhost:8080/api/actors/1" } } } ], "_links": { "self": { "href": "http://localhost:8080/api/actors/1" } } } ] } }
Drop me your questions in comments.
Happy Learning !!