I have a standard Spring data JPA and Spring data Rest setup which, correctly, returns associations as links to the correct resources.
{
"id": 1,
"version": 2,
"date": "2011-11-22",
"description": "XPTO",
"_links": {
"self": {
"href": "http://localhost:8000/api/domain/1"
},
"otherDomain": {
"href": "http://localhost:8000/api/domain/1/otherDomain"
}
}
}
However in some requests i would like to have the association to the "otherDomain" expanded (so the client does not have to do N+1 requests to get the full data).
Is it possible to configure Spring Data Rest to handle the response in this way?
@RepositoryRestResource is used to set options on the public Repository interface - it will automatically create endpoints as appropriate based on the type of Repository that is being extended (i.e. CrudRepository/PagingAndSortingRepository/etc).
Crud Repository is the base interface and it acts as a marker interface. JPA also provides some extra methods related to JPA such as delete records in batch and flushing data directly to a database. It provides only CRUD functions like findOne, saves, etc. JPA repository also extends the PagingAndSorting repository.
Real-world applications should avoid using Spring Data REST because the entities are exposed as RESTful Services. The two most critical considerations in designing a RESTful service are the domain model and the consumers. Both of these parameters are ignored when using the Spring Data REST.
The default responses will have to stay the same to make sure the payloads for PUT
requests are symmetric to the ones GET
s return. However, Spring Data REST introduces a feature called projections (see the JIRA ticket for details) that works as follows:
You create a dedicated interface and add all properties that you want to include in the response:
public interface MyProjection {
String getMyProperty();
MyRelatedObject getOtherDomain();
}
You can either
@Projection
and place it in the very same package as the domain type or a subpackage of itRepositoryRestConfiguration
and call projectionConfiguration().addProjection(…)
manually (by extending RepositoryRestMvcConfiguration
and overriding configureRepositoryRestConfiguration(…)
).This will cause the resources exposed for the domain type to accept a projection
parameter (name also configurable ProjectionConfiguration
) with the name of the projection. If given, we will skip the default rendering (which includes rendering links to related entities instead of embedding them) and let Jackson render a proxy backing the given interface.
An example of that can also be found in the Spring RESTBucks project. See the OrderProjection
for the interface definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With