Spring Boot REST Resource not showing linked objects (sets)

﹥>﹥吖頭↗ 提交于 2019-12-24 15:59:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!