Spring HATEOAS – Embedded Collection Model Name

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:

  1. value or itemRelation – is used when referring to a single resource.
  2. 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 !!

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.