Search code examples
hateoasspring-hateoas

How do you add multiple links of the same type to a resource using Spring HATEOAS?


The HAL spec that I am working with says that you can have multiple links of the same type on a resource like this:

{
    "_links": {
      "items": [{
          "href": "/first_item"
      },{
          "href": "/second_item"
      }]
    }
}

However Spring ResourceSupport type only seems to have an add() method that adds a single link. So I can write

order.add(linkTo(methodOn(OrderController.class).order(id)).withRel("item"));

to add one such, but I can't see how to get an array of them with a ref as items, as per the spec.


Solution

  • If you call ResourceSupport::add() twice (or more) with the same withRel value, it creates an array ref with that name containing each of the items.