I am using Spring Boot and Spring HATEOAS to build a REST API.
I have 2 simple objects. Let’s say:
// Model @Entity public class Person { private String name; private Address address; // ... usual methods omitted for brievity } @Entity public class Address { private String street; private String city; // ... } // Repository. It exposes directly a REST service public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {} // Application entry point @ComponentScan @EnableAutoConfiguration @EnableJpaRepositories @Import(RepositoryRestMvcConfiguration.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
This simple project creates output like the following:
{ "_links": { "self": { "href": "http://localhost:8080/persons{?page,size,sort}", "templated": true } }, "_embedded": { "persons": [ { "name": "Some name", "_links": { "self": { "href": "http://localhost:8080/persons/1" }, "address": { "href": "http://localhost:8080/persons/1/address" } } } ] } }
Fine, but I would like the application to send the Address object directly in the response. In order not to have to query the URL of the address.
Something like:
... "persons": [ { "name": "Some name", "address": { "street": "Some street name" "city": "Some city name" } "_links": { "self": { "href": "http://localhost:8080/persons/1" }, "address": { "href": "http://localhost:8080/persons/1/address" } } } ] ...
Are there any configuration to do that? I could not find any configuration about it in Spring HATEOAS docs. And this is the default behavior when using only regular Spring controllers.
Answer
The latest release of Spring Data REST’s docs illustrate excerpt projections. This provides an alternative default view of a collection of data.
Your use case is the exact angle it was originally designed for.