我的项目中有两个域对象Document
和Project
。 Document
与每个Project
相关联。我使用Spring-Data-Rest及其Repository
抽象,所以我有这个:
@Entity
public class Project extends AbstractLongIdEntity {
@Column(length=50,nullable=false)
private String title;
@Column(length=200,nullable=true)
private String description;
...
}
@Entity
public class Document extends AbstractLongIdEntity {
@Column(length=50,nullable=false)
private String title = "New Diagram";
@Column(length=200,nullable=true)
private String description;
public Document() {
}
public Document(String title, String description, Project project) {
super();
this.title = title;
this.description = description;
this.project = project;
}
@ManyToOne(targetEntity=Project.class, optional=false)
private Project project;
...
}
当我通过HTTP获取Document
时,我得到了回复:
[DEBUG] TEST - Response: 201 {
"title" : "My Document",
"description" : "Some name for a document",
"dateCreated" : "2018-02-13T06:33:14.397+0000",
"lastUpdated" : null,
"internalId" : 1,
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/documents/1"
},
"document" : {
"href" : "http://localhost:8080/api/documents/1"
},
"currentRevision" : {
"href" : "http://localhost:8080/api/documents/1/currentRevision"
},
"project" : {
"href" : "http://localhost:8080/api/documents/1/project"
}
}
}
但是,我无法首先回复相同的内容以创建Document
。我发现的最好的是我可以发布这个:
{
"title" : "My Document",
"description" : "Some name for a document",
"project" : "http://localhost:8080/api/projects/1",
"currentRevision" : null,
"dateCreated" : 1518503594397,
"lastUpdated" : null
}
然而,这似乎很奇怪,因为:
a)我现在在对象中嵌入了一个未命名的无类型链接,这不是非常HATEAOS(尽管Spring似乎正确地反序列化了它)。
b)我现在必须创建一个单独的类DocumentResource
,如下所示:
public class DocumentResource extends ResourceSupport {
public String title;
public String description;
public String project;
...
}
其中,Project
是String
。这是一个痛苦,因为我现在基本上有两个非常相似的域对象。
所以问题是:在HATEOAS / Spring Data Rest中POST新实体并让它们在数据库中创建关系的正确方法是什么?
我使用的是Spring Boot 1.5.10,它似乎带来了Spring-Data-Rest 2.6.10和Spring-Hateoas 0.23.0。
感谢
答案 0 :(得分:0)
您可以尝试这样发布:
{
"title" : "My Document",
"description" : "Some name for a document",
"project" : "/projects/1",
"currentRevision" : null,
"dateCreated" : 1518503594397,
"lastUpdated" : null
}