Spring Hateoas, by default, produces JSON containing collection names as classNameList format. We can customize the name generated for the embedded collection model using @Relation tag.
1. @Relation Annotation to Customize the 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:
valueoritemRelation– is used when referring to a single resource.collectionRelation– is used when referring to a collection of resources.
Example Usage
@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. Demo
2.1. Default Generated Names
Look at the default generated name albumModelList.
{
"_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. Custom Name with @Relation
After using the annotation on AlbumModel, the generated JSON response have the new name for the collection i.e. albums.
{
"_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"
}
}
}
]
}
}
Happy Learning !!
Comments