简体   繁体   中英

How to return representations of associations in a Spring Data REST resource?

There are following URLS - /users/2/profile , /users/2/userPosts

I need to concat output of both Spring Data REST results in server side and build single JSON from them and send on different URL /users/2/custom .

So, I am thinking to make 2 calls to SDR urls from Spring MVC, can we do this using RestTemplate and some JSON concat utility , here server and database is on same machine so RestTemplate will probably have localhost

An example will help

You might rather want to look into the projections feature of Spring Data REST which allows you to craft custom responses by using interfaces as described in this blog post .

As both properties ( profile and userPosts ) seem to be associations of a user item resource it should be sufficient to do something like this:

@Projection(types = User.class)
interface UserWithDetails {

  // List getters for basic properties you want to expose…

  // Add dedicated getters for associations to be included

  Profile getProfile();

  List<Post> getUserPosts();
}

Clients can now pass a projection parameter to the resources exposed to see the expanded representation.

As an alternative, you can create these kinds of interfaces for Profile and Post and configure @RepositoryRestResource on the repositories for both of these types to contain excerptProjection = YourProjectionInterface.class . This will cause the projections to be rendered whenever an association is included in the response (ie an actually-linked-to-resource could be embedded).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM