Spring数据REST:使用适当的HTTP方法更新资源的关联

时间:2014-03-19 08:14:12

标签: spring-data-rest

我正在使用Spring Data REST,我正在尝试使用Spring REST更改多对一关系,但我无法使用正确的http调用。

我的实体看起来像这样(像POST等创建的基本调用工作正常):

{
  "id" : 70,
  "productId" : yyy,
  "productdiscount" : 10,
  "version" : 0,
  "description" : "xxx",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/rest/rules/70"
    },
    "timedefinition" : {
      "href" : "http://localhost:8080/rest/rules/70/timedefinition"
    }
  }
}

我想将ID为1的当前时间定义更改为ID 2。

我尝试了很多不同的错误调用类型。以下电话不起作用。

 curl -X PUT -H "Content-Type: text/uri-list" -d 'http://localhost:8080/rest/timedefinition/1' http://localhost:8080/rest/rules/70/timedefinition

收到以下错误:

无法从类型java.lang.String转换为类型domain.TimeDefinition值为'0';嵌套异常是java.lang.IllegalArgumentException:为类domain.TimeDefinition提供了错误类型的id。预期:类java.lang.Integer,得到类java.lang.Long

另一个例子是:

curl -X PUT -H "Content-Type: application/json" -d '{"timedefinition": {"href" : "http://localhost:8080/rest/timedefinition/0", "rel" : "timedefinition"} }' http://localhost:8080/rest/rules/70/timedefinition

我得到的错误是:

“message”:“必须只发送1个链接来更新不是List或Map的属性引用。”

http://docs.spring.io/spring-data/rest/docs/2.0.1.RELEASE/reference/html/的主要参考资料不能很好地提供有关上述主题的大量信息。

非常感谢有关更新实体关联的正确REST查询格式的任何见解和解释!

3 个答案:

答案 0 :(得分:11)

正确答案就像我的评论一样:

curl -v -X PUT -H "Content-Type: text/uri-list" -d "http://localhost:8080/rest/timedefinition/0" http://localhost:8080/rest/rules/70/timedefinition

答案 1 :(得分:3)

spring-data-rest-webmvc:3.2.0-RELEASE中存在一个错误,该错误会在每次发送PUT以创建一对一关联时抛出此错误。

将spring-boot-starter-parent从2.2.0.RELEASE更改为2.2.1.RELEASE可以解决此问题。您还可以手动将spring-data-rest-webmvc覆盖为3.2.1.RELEASE

相关提交:https://github.com/spring-projects/spring-data-rest/commit/202a8aa30221b81dece183b74d81278deaf45321

答案 2 :(得分:-1)

您还可以通过将关系嵌入 _links 节点来使用application / json内容类型。

curl -X PUT -H "Content-Type: application/json" -d '{"_links":{"timedefinition": {"href" : "http://localhost:8080/rest/timedefinition/0", "rel" : "timedefinition"} }}' http://localhost:8080/rest/rules/70/timedefinition