2

Is it possible in spring data rest to embed the data for relationships of the primary resource in the HAL response?

The reasoning is that in some cases the client knows she will need the Child resource and the School and Pets relationships at once.

Using links this information can be requested in n requests, but ideally it would be possible to do in 1.

Note: n-levels deep would be great (JSON-API supports this) but for now even 1 level deep would be sufficient.

This is obviously possible according the HAL spec, and even possible using plain spring-hateoas (see this example).

  • Is this possible in any fashion with spring-data-rest?
  • Is it possible without a lot of boiler plate code and essentially rewriting bits of SDR?

If so, how is done? Examples would be most welcome.

Note that ALL the resources in question should be top-level resources, so no using @RestResource(exported = false) and getting them inlined as advocated by Oliver here.

Community
  • 1
  • 1
Casey
  • 6,166
  • 3
  • 35
  • 42

1 Answers1

2

You can define a Projection that would in-line the association data:

See:

http://docs.spring.io/spring-data/rest/docs/current/reference/html/#projections-excerpts

8.3. Excerpting commonly accessed data A common situation with REST services arises when you compose domain objects. For example, a Person is stored in one table and their related Address is stored in another. By default, Spring Data REST will serve up the person’s address as a URI the client must navigate. But if it’s common for consumers to always fetch this extra piece of data, an excerpt projection can go ahead and inline this extra piece of data, saving you an extra GET

@Projection(name = "withAssociations", types = { MyEntity.class })
public interface WithAssocationsProjection{

   //method names match the getter methods in the corresponding Entity

   List<School> getSchools();

   List<Pet> getPets();

   //you can also in-line a subset of data or have a further level 
   //of data in-lined for the association by
   //specifying a further projection as the Collection Type.


   List<ChildProjection> getChildren();
}

Clients can then request a specific view of the data like:

http://localhost:9090/api/myEntities?projection=withAssociations

http://localhost:9090/api/myEntities/123?projection=withAssociations

Alan Hay
  • 22,665
  • 4
  • 56
  • 110
  • Unfortunately projections don't answer this question exactly. Projections inline the data, but not using the `_embedded` key in HAL. If the same entity is inlined by multiple parent entities, then it will be repeated in the payload, wasting lots of space. – Casey Feb 15 '17 at 13:37
  • I guess a custom controller would be the way forward then. – Alan Hay Feb 15 '17 at 13:46