Spring Data REST URI与实体ID

时间:2012-10-14 06:49:25

标签: spring rest spring-data-jpa spring-data-rest spring-hateoas

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

假设客户端应用程序想要使用关联的Ticket资源创建新的TicketCategory资源。我想针对远程Spring Data REST端点发布TicketTicket还没有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建立实体之间关系的方案。我不知道这是否是目前可用的唯一方法,但似乎这种方法需要在初始帖子上保留关联null,然后用后续帖子更新它。在上面的情况下,这是不合需要的,因为门票需要类别字段(@NotNull)。

2 个答案:

答案 0 :(得分: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"
  }
}

答案 1 :(得分:11)

显然在较新版本的Spring Data Rest中,应该这样做:

POST /tickets
Content-Type: application/json

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

Oliver Gierke在Spring Data Rest 2.0.0.RELEASE Breaks Code Working Previously With RC1

的评论