【问题标题】:Spring Boot REST Resource not showing linked objects (sets)Spring Boot REST 资源未显示链接对象(集)
【发布时间】:2015-10-15 18:29:28
【问题描述】:

我有一个数据库和一些类。这些类与OneToMany 链接,依此类推。

如果我用 spring 打印对象本身,它会包含所有内容。但是如果我使用 Resource 功能打印它,它只包含变量,这些变量不是集合或与其他类链接。

如何将集合添加到输出中?

【问题讨论】:

  • 你在使用 Spring Data REST 吗?如果是这样,请查看预测。
  • 我正在使用 Spring Data REST。 “投影”是什么意思?

标签: java spring spring-boot spring-data-rest spring-hateoas


【解决方案1】:

默认情况下,Spring Data REST 不显示关联资源,除了链接。如果您希望,您必须定义描述您想要查看的字段的投影,无论它们是您描述的简单字段还是相关资源。见

http://docs.spring.io/spring-data/rest/docs/current/reference/html/#projections-excerpts

例如,假设您有一个 Service 资源,该资源与 serviceTypeserviceGroupownerserviceInstancesdocLinks 等资源相关联。如果您希望这些显示在响应正文中,您可以创建一个投影:

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();
}

然后获取带有投影的 URL:

http://localhost:8080/api/services/15?projection=serviceDetails

结果将包括投影属性:

{
  "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
  }, ... ],
  ...
}

【讨论】:

  • 这真的是唯一的解决方案吗?我的意思是我有所有数据库条目的类,现在我也必须制作接口?
  • 仅在您实际需要内联数据的情况下。它不同于例如JPA/Hibernate 你可能有延迟加载,因为有了 HTTP 响应,你不会有一个代理来延迟加载。如果 SDR 默认显示在链接足够的许多上下文中会导致大量响应(具有相应的连接/有效负载)的所有关联资源。因此,SDR 在不加入的情况下返回所有可以加入的内容,但提供了必要时加入的选项。
  • 我在其他情况下使用Pageable,默认情况下它会向我显示内容。有什么办法吗?
  • 有时我得到所有的子信息,有时我没有... ||有没有办法从特定的电话中隐藏一些东西? (例如“根”元素?-我总是得到所有带有密码的帐户...)
猜你喜欢
  • 2019-01-04
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 2019-11-27
  • 2017-06-21
  • 2018-09-04
  • 2016-06-06
相关资源
最近更新 更多