问题
I've a database and some classes. These classes are linked with OneToMany
, and so on.
If I print the object itself with spring it contains everything. But if I print it with the Resource feature, it contains only the variables, which are no collections or linked otherwise with an other class.
How can I add the collections to the output?
回答1:
By default Spring Data REST does not show associated resources except as links. If you want that you have to define projections that describe the fields you want to see, whether they're simple fields like the ones you describe or associated resources. See
http://docs.spring.io/spring-data/rest/docs/current/reference/html/#projections-excerpts
For example say you have a Service
resource with associations to resources like serviceType
, serviceGroup
, owner
, serviceInstances
and docLinks
. If you want those to show up in the response body you can create a projection:
package my.app.entity.projection;
import org.springframework.data.rest.core.config.Projection;
...
@Projection(name = "serviceDetails", types = Service.class)
public interface ServiceDetails {
String getKey();
String getName();
ServiceType getType();
ServiceGroup getGroup();
Person getOwner();
List<ServiceInstance> getServiceInstances();
List<DocLink> getDocLinks();
String getPlatform();
}
Then GET your URL with the projection:
http://localhost:8080/api/services/15?projection=serviceDetails
The result will include the projected properties:
{
"name" : "MegaphoneService",
"key" : "megaphone",
"type" : {
"key" : "application",
"name" : "User Application",
"description" : "A service that allows users to use a megaphone."
},
"owner" : null,
"serviceInstances" : [ {
"key" : "megaphone-a-dr",
"description" : null,
"loadBalanced" : true,
"minCapacityDeploy" : null,
"minCapacityOps" : 50
}, ... ],
...
}
来源:https://stackoverflow.com/questions/33155909/spring-boot-rest-resource-not-showing-linked-objects-sets