HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring 5 / Spring HATEOAS / Spring HATEOAS – Pagination links

Spring HATEOAS – Pagination links

Learn to build automatic pagination links in spring hateaos application using PagedModel and PagedResourcesAssembler classes.

1. Use PagingAndSortingRepository

First thing, we need to use PagingAndSortingRepository repository which provides methods to retrieve entities using the pagination and sorting abstraction.

It is important because we do not want to rewrite the JPA queries to read data in paging fashion, as it is available just by implementing this simple interface.

import org.springframework.data.repository.PagingAndSortingRepository;
import com.howtodoinjava.rest.entity.AlbumEntity;

public interface AlbumRepository 
	extends PagingAndSortingRepository<AlbumEntity, Long>{

}

2. Create PagedModel using PagedResourcesAssembler

  • To enable automatic pagination links, we must use PagedModel provided by spring hateoas module which helps in creating representations of pageable collections.
  • PagedResourcesAssembler accepts the JPA entities list, and convert it to PagedModel.
  • Additionally, we can use RepresentationModelAssembler to convert JPA entities into CollectionModel having custom resource representation.
  • Finally, PagedModel is returned as API response from web controller.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.PagedModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.howtodoinjava.rest.assembers.AlbumModelAssembler;
import com.howtodoinjava.rest.entity.AlbumEntity;
import com.howtodoinjava.rest.model.AlbumModel;
import com.howtodoinjava.rest.repository.AlbumRepository;

@RestController
public class WebController 
{
	@Autowired
	private AlbumRepository albumRepository;

	@Autowired
	private AlbumModelAssembler albumModelAssembler;

	@Autowired
	private PagedResourcesAssembler<AlbumEntity> pagedResourcesAssembler;

	@GetMapping("/api/albums-list")
	public ResponseEntity<PagedModel<AlbumModel>> getAllAlbums(Pageable pageable) 
	{
		Page<AlbumEntity> albumEntities = albumRepository.findAll(pageable);
		
		PagedModel<AlbumModel> collModel = pagedResourcesAssembler
							.toModel(albumEntities, albumModelAssembler);
		
		return new ResponseEntity<>(collModel,HttpStatus.OK);
	}
}

3. Verify pagination links

Run the application and invoke REST API with paging request parameters.

Page numbers start with zero (0).

  • http://localhost:8080/api/albums-list?page=1&size=2&sort=title,desc
{
	"_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"
                    }
                }
            }
        ]
    }
}

We can verify different pagination and sorting options in URL using query parameters and they will work.

Happy Learning !!

Sourcecode Download

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Hubert

    May 24, 2020

    Why do I always have the “page” sections at the end of the Json file ?

    • Lokesh Gupta

      May 24, 2020

      I do not remember but perhaps I did some formatting to the output.

Comments are closed on this article!

Search Tutorials

Spring HATEOAS Tutorial

  • HATEOAS – Introduction
  • HATEOAS – Pagination links
  • HATEOAS – Embedded Name

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces