Spring Data Rest - 在 _embedded 中包含嵌套资源

2023-12-02

我正在为购物清单开发一个 Spring Boot 应用程序。 为此,我使用 Spring Data Rest 通过 REST API 导出我的实体。

我的架构看起来像这样

我有一个购物项目:

public class ShoppingItem {
@Id
@GeneratedValue
private Long id;

@ManyToOne
@JoinColumn(name = "articleId", nullable = false)
private Article article;

private Integer number;

private boolean bought;

public ShoppingItem(){
    this.article = null;
    this.number = 0;
    this.bought = false;
}

}

该购物商品包含一篇作为导出资源的文章。

The Article看起来像这样:

public class Article {

@Id
@GeneratedValue
private Long id;

@Column(unique = true)
private String name;

private Integer price;
}

当我请求 ShoppingItem 时,答案如下所示:

{
  id: 94,
  number: 1,
  bought: false,
  _links: {
    self: {
      href: "https://myDomain.tld/api/shoppingItems/94"
    },
    article: {
      href: "https://myDomain.tld/api/shoppingItems/94/article"
    }
  }
}

是否可以包括Article在 _embedded 中请求时ShoppingItem所以响应看起来像这样?

{
  id: 94,
  number: 1,
  bought: false,
  _links: {
    self: {
      href: "https://myDomain.tld/api/shoppingItems/94"
    },
    article: {
      href: "https://myDomain.tld/api/shoppingItems/94/article"
    }
  },
  _embedded: {
    article: {
      id: '999',
      name: 'someThing',
      price: '1.99'
    }
  }
}

update 1使用时Accept: application/x-spring-data-verbose+json

响应如下所示:

{
  id: 94
  number: 1
  bought: false
  links: [2]
    0:  {
      rel: "self"
      href: "https://wg.yannic-klem.de/api/shoppingItems/94"
    }-
    1:  {
      rel: "article"
      href: "https://wg.yannic-klem.de/api/shoppingItems/94/article"
    }-
  -
  content: [0]

}

内容列表始终为空:(

更新2:

有关我的架构的更多信息,请随时查看我的 Github 存储库:https://github.com/Yannic92/ShoppingList/tree/master/src/main/java/de/klem/shopping


尝试添加这个Accept发出请求时的标头:

Accept: application/x-spring-data-verbose+json

另外,看看这个帖子其中详细解释了这一点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Data Rest - 在 _embedded 中包含嵌套资源 的相关文章

随机推荐