How to correctly use PagedResourcesAssembler from Spring Data?

You seem to have already found out about the proper way to use but I’d like to go into some of the details here a bit for others to find as well. I went into similar detail about PagedResourceAssembler in this answer.

Representation models

Spring HATEOAS ships with a variety of base classes for representation models that make it easy to create representations equipped with links. There are three types of classes provided out of the box:

  • Resource – an item resource. Effectively to wrap around some DTO or entity that captures a single item and enriches it with links.
  • Resources – a collection resource, that can be a collection of somethings but usually are a collection of Resource instances.
  • PagedResources – an extension of Resources that captures additional pagination information like the number of total pages etc.

All of these classes derive from ResourceSupport, which is a basic container for Link instances.

Resource assemblers

A ResourceAssembler is now the mitigating component to convert your domain objects or DTOs into such resource instances. The important part here is, that it turns one source object into one target object.

So the PagedResourcesAssembler will take a Spring Data Page instance and transform it into a PagedResources instance by evaluating the Page and creating the necessary PageMetadata as well as the prev and next links to navigate the pages. By default – and this is probably the interesting part here – it will use a plain SimplePagedResourceAssembler (an inner class of PRA) to transform the individual elements of the page into nested Resource instances.

To allow to customize this, PRA has additional toResource(…) methods that take a delegate ResourceAssembler to process the individual items. So you end up with something like this:

 class UserResource extends ResourceSupport { … }

 class UserResourceAssembler extends ResourceAssemblerSupport<User, UserResource> { … }

And the client code now looking something like this:

 PagedResourcesAssembler<User> parAssembler = … // obtain via DI
 UserResourceAssembler userResourceAssembler = … // obtain via DI

 Page<User> users = userRepository.findAll(new PageRequest(0, 10));

 // Tell PAR to use the user assembler for individual items.
 PagedResources<UserResource> pagedUserResource = parAssembler.toResource(
   users, userResourceAssembler);

Outlook

As of the upcoming Spring Data Commons 1.7 RC1 (and Spring HATEOAS 0.9 transitively) the prev and next links will be generated as RFC6540 compliant URI templates to expose the pagination request parameters configured in the HandlerMethodArgumentResolvers for Pageable and Sort.

The configuration you’ve shown above can be simplified by annotating the config class with @EnableSpringDataWebSupport which would let you get rid off all the explicit bean declarations.

Leave a Comment

tech