8

Spring Data REST(尤其是 Spring HATEOAS)将 RESTful ID(即 URI)与实体 ID 分离,我在保存新对象时无法将它们链接起来。请参阅https://github.com/SpringSource/spring-data-rest/issues/13上有关此解耦的有趣讨论。

假设客户端应用程序想要创建Ticket具有关联资源的新TicketCategory资源。我想Ticket针对远程 Spring Data REST 端点发布。因为是新的Ticket,所以还没有ID。有TicketCategory一个 ID,但在客户端上它是上面讨论的 URI。因此,当我保存 时Ticket,Spring Data REST 将 传递Ticket给不喜欢它的 Spring Data JPA:Spring Data JPA 认为TicketCategory- 没有实体 ID - 是暂时的:

org.hibernate.TransientPropertyValueException:
    Not-null property references a transient value -
    transient instance must be saved before current operation:
    com.springinpractice.ch13.helpdesk.model.Ticket.category ->
    com.springinpractice.ch13.helpdesk.model.TicketCategory

更新:文档位于

https://github.com/SpringSource/spring-data-rest/wiki/JPA-Repository-REST-Exporter

有一个名为“更新关系”的部分描述了使用 HTTP POST 建立实体之间关系的方案。我不知道这是否是当前唯一可用的方法,但似乎这种方法需要在初始帖子中将关联保留为空,然后使用后续帖子对其进行更新。在上述情况下,这是不可取的,因为工单需要类别字段 ( @NotNull)。

4

2 回答 2

12

你看过https://github.com/SpringSource/spring-data-rest/wiki/Embedded-Entity-references-in-complex-object-graphs吗?

简而言之,如果导出器发现链接对象代替关系或托管对象(另一个具有导出存储库的实体),它将取消引用它们。

假设您的链接属性称为“类别”,那么您可以创建一个新的票证,如:

POST /tickets
Content-Type: application/json

{
  "description": "Description of the ticket or issue",
  "category": {
    "rel": "category.Category",
    "href": "http://localhost:8080/categories/1"
  }
}
于 2012-10-23T13:30:54.380 回答
11

Apprently in the newer versions of Spring Data Rest, this should do it:

POST /tickets
Content-Type: application/json

{
  "description": "Description of the ticket or issue",
  "category": "http://localhost:8080/categories/1"
}

Going by Oliver Gierke's comment at Spring Data Rest 2.0.0.RELEASE Breaks Code Working Previously With RC1

于 2014-06-14T20:44:33.483 回答