英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论