【问题标题】:Spring Data REST - add item to associated collectionSpring Data REST - 将项目添加到关联集合
【发布时间】:2015-04-17 23:29:13
【问题描述】:

我正在尝试弄清楚如何使用 Spring Data Rest 将项目添加到关联的集合中。

根据Spring Data REST documentation,集合支持POST方式,所以

  curl -i -X POST -H 'Content-type: text/uri-list' -d 'http://localhost:8080/artifacts/1' http://localhost:8080/collectors/1/artifacts

应该将工件添加到(但为空的)集合中。不幸的是,它没有:

HTTP/1.1 405 Method Not Allowed
Server: Apache-Coyote/1.1
Allow: GET, DELETE, PATCH, PUT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 17 Apr 2015 22:54:59 GMT

{"timestamp":1429311299117,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/collectors/1/artifacts"}

我的实体:

@Data
@Entity
public class Collector {
    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "owner")
    private List<Artifact> artifacts;
}

@Data
@Entity
@Accessors(chain = true, fluent = true)
public class Artifact {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    @ManyToOne
    @JoinColumn(name = "collector_id")
    private Collector owner;
}

完整代码在Github

我做错了什么?

【问题讨论】:

  • 似乎您发布到错误的端点。确保启动应用时 Spring 数据生成的映射与模式和方法匹配。
  • 端点很好,我可以从同一端点获取工件列表。我只是无法在列表中添加新的。
  • 首先你不应该序列化实体对象。使用域对象。然后确保你有合适的构造函数可用。
  • 我不确定你是什么意思,@Vaelyr。 Lombok 负责我的构造函数(大部分时间)。实体对象本质上必须是可序列化的。
  • API 应该对实体对象一无所知。为了获得良好的实践,您应该将它们映射到与您的 API 对话的单独 DTO 对象,服务返回映射到 DTO-s 的实体对象。如果您打算使用注释进行任何类型的验证,您将被它们淹没。无论如何,我看不到您通过 curl 发布的内容? -d 'http://localhost:8080/artifacts/1' 好像错了?您应该传入 json:-d '{ "name" : "John", "artifacts" : [{ "articaftName" : "test" }] }'

标签: java spring http-post model-associations spring-data-rest


【解决方案1】:

问题是您使用的是 Spring Data Rest 2.2.2 附带的 Spring boot 1.2.4 版本。而且 Spring Data Rest 2.2.2 没有你需要的功能。

您需要的是 Spring Data Rest 2.3.1,您需要 supports the functionality

【讨论】:

    猜你喜欢
    • 2015-07-06
    • 2016-08-27
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 2018-10-08
    • 2018-09-27
    相关资源
    最近更新 更多