Spring Data REST URI与实体ID

Wil*_*ler 7 rest spring 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资源的新资源.我想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
Run Code Online (Sandbox Code Playgroud)

更新:文档在

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

有一个名为"更新关系"的部分,描述了使用HTTP POST建立实体之间关系的方案.我不知道这是否是目前可用的唯一方法,但似乎这种方法需要在初始帖子上保留关联null,然后用后续帖子更新它.在上面的情况下,这是不合需要的,因为类别字段@NotNull对于票证是必需的().

小智 12

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

简单地说,如果导出器找到它们代替关系或托管对象(具有导出的存储库的另一个实体),则导出器将取消引用它们.

假设您的链接属性被称为"类别",那么您可以创建一个新的Ticket,如:

POST /tickets
Content-Type: application/json

{
  "description": "Description of the ticket or issue",
  "category": {
    "rel": "category.Category",
    "href": "http://localhost:8080/categories/1"
  }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ing 11

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

POST /tickets
Content-Type: application/json

{
  "description": "Description of the ticket or issue",
  "category": "http://localhost:8080/categories/1"
}
Run Code Online (Sandbox Code Playgroud)

参阅 Oliver GierkeSpring Data Rest 2.0.0的评论.RELEASE以前使用RC1打破代码工作

  • 您能否为您使用的票证和类别发布两个实体类的代码。您如何准确注释两者之间的关系?ManyToOne?还是一对多?关系的哪一方面?与Cascade.All ??? 或不?是否添加@NotNull注释(对我不起作用) (2认同)