【问题标题】:Posting With Spring HATEOAS / Spring Data Rest使用 Spring HATEOAS / Spring Data Rest 发布
【发布时间】:2018-07-23 11:24:09
【问题描述】:

我的项目中有两个域对象,DocumentProjectDocuments 与每个 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 中发布新实体并让它们在数据库中创建关系的正确方法是什么?

我使用的是 Spring Boot 1.5.10,它似乎引入了 Spring-Data-Rest 2.6.10 和 Spring-Hateoas 0.23.0。

谢谢

【问题讨论】:

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


    【解决方案1】:

    你可以试试这样发帖:

    {
      "title" : "My Document",
      "description" : "Some name for a document",
      "project" : "/projects/1",
      "currentRevision" : null,
      "dateCreated" : 1518503594397,
      "lastUpdated" : null
    }
    

    【讨论】:

    • 嗨,保罗,是的,我提到了这种方法,以及为什么它在问题中不是很好。它有效,有点,但这不是我所追求的
    猜你喜欢
    • 2013-10-31
    • 2014-03-07
    • 2014-07-05
    • 2014-08-16
    • 2016-05-23
    • 1970-01-01
    • 2016-02-07
    • 2018-11-26
    • 1970-01-01
    相关资源
    最近更新 更多