Spring Data REST(尤其是 Spring HATEOAS)将 RESTful ID(即 URI)与实体 ID 解耦,并且在保存新对象时我无法将它们链接起来。请参阅 https://github.com/SpringSource/spring-data-rest/issues/13 关于这种解耦的有趣讨论。 .
假设客户端应用想要创建一个具有关联 TicketCategory
资源的新 Ticket
资源。我想针对远程 Spring Data REST 端点发布Ticket
。 Ticket
由于是新的,因此还没有 ID。 TicketCategory
有一个 ID,但在客户端上,根据上面的讨论,它是一个 URI。因此,当我保存 Ticket
时,Spring Data REST 将 Ticket
传递给 Spring Data JPA,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
)。
最佳答案
简单地说,如果导出器发现链接对象代替了关系或托管对象(具有导出的存储库的另一个实体),则导出器将取消引用链接对象。
假设您的链接属性称为“类别”,那么您可以创建一个新的票证,例如:
POST /tickets
Content-Type: application/json
{
"description": "Description of the ticket or issue",
"category": {
"rel": "category.Category",
"href": "http://localhost:8080/categories/1"
}
}
关于Spring Data REST URI 与实体 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12879975/