我有一个需要接受来自客户端的任意字段的实体,让我们将实体称为Blob
。我已使用@JsonAnyGetter
/ @JsonAnySetter
注释定义了我的实体,以捕获未明确映射的任何字段:
@Document
public class Blob {
@Id
private ObjectId id;
private Map<String, Object> additionalFields = new HashMap<>();
Blob() {
}
public ObjectId getId() {
return id;
}
@JsonAnySetter
public void setAdditionalFields(final String key, final Object value) {
this.additionalFields.put(key, value);
}
@JsonAnyGetter
public Map<String, Object> getAdditionalFields() {
return additionalFields;
}
}
然后我有一个rest存储库给我基本的CRUD端点:
public interface BlobRepository extends CrudRepository<Blob, ObjectId> {
}
POST按预期工作,响应为我提供了所有字段:
POST /blobs HTTP/1.1
Content-Type: application/json
Accept: application/json
{
"name": "bob",
"size": "small",
"color": "green"
}
HTTP/1.1 201
Location: http://localhost:8080/blobs/5919e2e292034b6765507cd4
Content-Type: application/json;charset=UTF-8
{
"name" : "bob",
"size" : "small",
"color": "green",
"_links" : {
"self" : {
"href" : "http://localhost:8080/blobs/5919e2e292034b6765507cd4"
},
"blob" : {
"href" : "http://localhost:8080/blobs/5919e2e292034b6765507cd4"
}
}
}
问题是当我尝试使用PUT请求更新现有blob时:
PUT /blobs/5919e2e292034b6765507cd4 HTTP/1.1
Content-Type: application/json
Accept: application/json
{
"name": "bobby",
"size": "large",
"color": "blue"
}
HTTP/1.1 200
Location: http://localhost:8080/blobs/5919e2e292034b6765507cd4
Content-Type: application/json;charset=UTF-8
{
"name" : "bob",
"size" : "small",
"color": "green",
"_links" : {
"self" : {
"href" : "http://localhost:8080/blobs/5919d09d92034b5b219802b3"
},
"blob" : {
"href" : "http://localhost:8080/blobs/5919d09d92034b5b219802b3"
}
}
}
不接受任何新字段,只保留旧值。但令人沮丧的是,PATCH请求按预期工作:
PATCH /blobs/5919e2e292034b6765507cd4 HTTP/1.1
Content-Type: application/json
Accept: application/json
{
"name": "bobby",
"size": "large",
"color": "blue"
}
HTTP/1.1 200
Location: http://localhost:8080/blobs/5919e2e292034b6765507cd4
Content-Type: application/json;charset=UTF-8
{
"name" : "bobby",
"size" : "large",
"color": "blue",
"_links" : {
"self" : {
"href" : "http://localhost:8080/blobs/5919d09d92034b5b219802b3"
},
"blob" : {
"href" : "http://localhost:8080/blobs/5919d09d92034b5b219802b3"
}
}
}
我可能错了,但我不认为这与PUT与PATCH的semtantics有关,因为我发送完整的对象将是我期望的所有字段PUT用新字段替换(或理想地合并)现有实体。
我创建了a repo with a minimal spring project以及一些显示问题的测试。任何通过都将不胜感激。