Spring 开机补丁

Spring boot PATCH

正如我阅读文档 (https://spring.io/guides/gs/accessing-data-rest/)

PUT replaces an entire record. Fields not supplied will be replaced with null. PATCH can be used to update a subset of items.

所以,我尝试为我的用户实体使用 PATCH,其中包含 2 个字段(名字和姓氏)

@RequestMapping(path="/user/{id}", method = RequestMethod.PATCH)
public User updateUser ( User user) {       
    return userRepository.save(user);
}

当我发送到:

localhost:8080/user/34

body 与 name: "user" and surname: "testSurname" 效果很好。 但是当我只发送 name (without surname) 时,surname 也会更新为 null.

如何防止 spring 启动时使用空值更新字段?

您没有在此处使用 Spring Data Rest。您正在使用 spring 数据 jpa 存储库 userRepository.save(department);

和Spring MVC 通过创建您的自定义 http 端点。

@RequestMapping(path="/user/{id}", method = RequestMethod.PATCH)
public User updateUser ( User user) {...

要查看您描述的补丁程序行为,您必须使用 spring data rest 公开的端点,而不是您创建的自定义端点。 当您创建自定义端点时,它将完全按照您的代码执行,spring 不会扰乱您的代码并改变行为。