Enable HAL serialization in Spring Boot for custom controller method

There’s a lot of aspects here:

  1. I doubt that the collection resource at /transactions really returns an individual transaction as you described. Those representations are returned for item resources.

  2. If TransactionRepository already is a PageableAndSortingRepository the collection resource can be tweaked by expanding the URI template exposed in the API root for the link named transactions. By default that’s a page, size and sort parameter. That means clients can request what you want to expose already.

  3. If you want to default the paging and sorting options, implementing a controller is the correct way. However, to achieve a representation like Spring Data REST exposes you need to return at least instances of ResourceSupport as this is the type the HAL mapping is registered for.

    There’s nothing magically here if you think about it. A plain entity does not have any links, the ResourcesSupport and types like Resource<T> allow you to wrap the entity and enrich it with links as you see fit. Spring Data REST basically does that for you using a lot of the knowledge about the domain and repository structure that’s available implicitly. You can reuse a lot of as shown below.

    There are a few helper you need to be aware of here:

    • PersistentEntityResourceAssembler – which is usually injected into the controller method. It renders a single entity in a Spring Data REST way, which means that associations pointing to managed types will be rendered as links etc.
    • PagedResourcesAssembler – usually injected into the controller instance. Takes care of preparing the items contained in the page, optionally by using a dedicated ResourceAssembler.

    What Spring Data REST basically does for pages is the following:

    PersistentEntityResourceAssembler entityAssembler = …;
    Resources<?> … = pagedResourcesAssembler.toResources(page, entityAssembler);
    

    That’s basically using the PagedResourcesAssembler with the PersistentEntityResourceAssembler to render the items.

    Returning that Resources instance should give you the representation design you expected.

Leave a Comment