I've been searching for a few days on how to implement a Spring REST API containing HATEOAS links + Pagination with Spring boot and JPA (No spring data rest) like this random example:
{
"_links": {
"first": {
"href": "http://localhost:8080/api/albums-list?page=0&size=2&sort=title,desc"
},
"prev": {
"href": "http://localhost:8080/api/albums-list?page=0&size=2&sort=title,desc"
},
"self": {
"href": "http://localhost:8080/api/albums-list?page=1&size=2&sort=title,desc"
},
"next": {
"href": "http://localhost:8080/api/albums-list?page=2&size=2&sort=title,desc"
},
"last": {
"href": "http://localhost:8080/api/albums-list?page=4&size=2&sort=title,desc"
}
},
"page": {
"size": 2,
"totalElements": 10,
"totalPages": 5,
"number": 1
},
"_embedded": {
"albums": [
{
"id": 7,
"title": "Top Hits Vol 7",
"description": "Top hits vol 7. description",
"releaseDate": "10-03-1987",
"actors": [
{
"id": 4,
"firstName": "Janice",
"lastName": "Preston",
"_links": {
"self": {
"href": "http://localhost:8080/api/actors/4"
}
}
}
],
"_links": {
"self": {
"href": "http://localhost:8080/api/actors/7"
}
}
},
{
"id": 6,
"title": "Top Hits Vol 6",
"description": "Top hits vol 6. description",
"releaseDate": "10-03-1986",
"actors": [
{
"id": 3,
"firstName": "Laverne",
"lastName": "Mann",
"_links": {
"self": {
"href": "http://localhost:8080/api/actors/3"
}
}
}
],
"_links": {
"self": {
"href": "http://localhost:8080/api/actors/6"
}
}
}
]
}
}
However, the solutions that I've found so far are ridiculously complicated or the amount of boilerplate are laughable This solution for instance: https://howtodoinjava.com/spring5/hateoas/pagination-links/ the tutorial on the page doesn't present it entirely but it requires you to create the entity, a model for the entity, and a long RepresentationModelAssemblerSupport full of boilerplate
I've tried this also: https://spring.io/guides/tutorials/rest/ However the nested classes (i have relations of one to many/many to one) don't get the links for HATEOAS:
{
"id": 3,
"nome": "Amazonas",
"uf": "AM",
"cidades": [
{
//no HATEOAS in here
"id": 10003,
"nome": null,
"instituicoes": [],
"uf": "AM"
},
{
"id": 219,
"nome": "Alvarães",
"instituicoes": [],
"uf": "AM"
}
],
"_links": {
"self": {
"href": "http://localhost:8080/api/v1/estados/estadoes/3"
},
"estadoes": {
"href": "http://localhost:8080/api/v1/estados/estadoes"
}
}
}
I mean, isn't there a simpler solution? Luckily for pagination PagingAndSortingRepository is useful but then having both pagination + HATEOAS, what a nightmare.
public class PostModelAssemblerSupport extends RepresentationModelAssemblerSupport<Post, PostModel> {
but it makes the method callpagedResourcesAssembler.toModel(posts, postModelAssemblerSupport);
undefined. – Ploch