用自动生成的ID更新带有特定ID的REST资源

huangapple go评论71阅读模式
英文:

REST PUT resource with ID while having auto-generated IDs

问题

我正在实现一个REST API,想要使用PUT方法来创建或更新资源。该资源通过一个ID进行标识,用户可以像这样发送ID:

{
    "id": 5,
    "name": "John"
}

Spring Boot Rest Controller接收这些消息并使用Spring Data Repository,其中包含自动生成的ID。如果数据库中存在具有此ID的记录,则会对其进行更新,否则将创建一个新记录并分配此ID。然而,这些ID是由Hibernate序列生成的。如果用户使用ID 5添加资源,但Hibernate序列当前位于编号2,我是否应该调整Hibernate序列?或者是否有更好的方法来解决这个问题?

英文:

I'm implementing a REST API and I want to use PUT method to create or update a resource. The resource is identified by an ID, which can be sent by user like this:

{
    "id": 5,
    "name": "John"
}

The Spring Boot Rest Controller accepts the messages and uses a Spring Data Repository, which has auto-generated IDs. If a record in DB with this ID exists, it will be updated, otherwise a new one with this ID will be created. However the IDs are created by Hibernate sequence. Should I move the Hibernate sequence if user adds resource with ID 5, but the Hibernate sequence is at number 2, or is there a better way how to handle this problem?

答案1

得分: 2

我认为不需要,你应该将POST/PUT API用于创建/更新,就像这样:

POST:/users
PUT:/users/{user_id}

请求体:
{
    "name": "John",
    ...
}
英文:

I believe not, you should separate POST/PUT API to create/update like

POST: /users
PUT:  /users/{user_id}

     body: {
     "name": "John",
     ...
     }

答案2

得分: 1

在Hibernate中,如果您想添加具有自动生成的ID的新实体,则不应传递ID列,或者如果您已经具有带有ID的实体,则应将ID字段设置为null

英文:

In Hibernate, if you want to add new Entity with auto-generated ID, you SHOULD NOT pass them ID column,or if you already have entity with ID, you should set ID field to null.

答案3

得分: 1

我建议你创建一个查询方法 GET:

GET:/users/{userId}

这将帮助你获取你的ID。

谢谢。

英文:

I suggest you to create a query method GET:

GET: /users/{userId}

This help you to get your ID.

Regards.

huangapple
  • 本文由 发表于 2020年9月15日 21:05:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63902490.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定