在我的应用程序中,我试图支持JSON补丁请求来应用部分更新我的实体,并且我在Spring数据rest库中直接使用Spring提供的patch的实现。
我无法使用Spring Patch实现来部分更新Java中的Maps,或者Spring实现无法支持这样的操作。
Spring Patch将JSON补丁操作转换为SPEL操作,对于具有固定属性(或字段)的POJO,一切都很好,但它似乎不适用于Maps,因为我认为"字段"是Map的键。
知道Spring在幕后将JSON路径转换为SPEL操作,我还尝试在PATCH负载中使用SPEL表示法,但没有任何结果。这就是我尝试过的
假设情况是这样的:
//Here is my object
public class Book {
public String author;
public String ISBN;
public Map<String, String> characters;
}
// Here I create a simple instance of the object
Book myBook = new Book();
myBook.author = "Me"
myBook.ISBN = "1234567890"
myBook.characters = new HashMap<>();
myBook.characters.put("protagonist", "Pinco");
myBook.characters.put("antagonist", "Pallo");
// Here the type of operations that work
[
{"op": "replace", "path": "/author", "value": "NewAuthor"},
{"op": "replace", "path": "/ISBN", "value": 0987654321 },
]
// I can also modify completely the Map if I want
[
{"op": "replace", "path": "/characters", "value": {"protagonist": "Pallo", "antagonist": "Pinco"} }
]
// But I can't update a single value in the map
[
{"op": "replace", "path": "/characters/protagonist", "value": "Pallo" },
{"op": "replace", "path": "/characters/antagonist", "value": "Pinco" }
]
// I've also tried weird stuff, but doesn't work
[
{"op": "replace", "path": "/characters[antagonist]", "value": "Pinco"}
]
我希望嵌套映射上的替换操作通过检查键来工作,但可能我做错了什么,或者我应该简单地用正则字段表示所有对象,比如POJO,这样才能工作。
对于所有其他尚未看到相应问题和拉取请求的人,在这里它似乎已经修复,只是为我们的项目验证了它(PATCHing aMap<Locale, String>
),它就起了作用。
参考:
- https://jira.spring.io/browse/DATAREST-1338
- https://github.com/spring-projects/spring-data-rest/pull/305/