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
)。