我绝对没有找到完全自动进行部分更新的明确方法(可以通过比较数据库和部分对象中的字段对象)。
我看到了一些轨道,例如:
MapperService
heavyResourceRepository
save(Map<String, Object> updates, String id)
的存储库类型使用方法copyProperty
方法 谢谢,可以使用 PATCH 方法,但我没有看到实现它的明确方法。
最佳答案
您可以使用 @RepositoryRestResource 来为您做这件事。
当您像这样导出端点时:
@RepositoryRestResource(path = "some_entity")
public interface SomeEntityRespostiory extends JpaRepository<SomeEntity, Integer> {
}
您将公开默认 CRUD 的所有选项,并且不需要 Controller 类。
您可以使用 PUT 替换所有实体字段。或者您可以使用 PATCH 仅替换实体中的某些字段。
此 PATCH 方法将负责仅更新您从有效负载中实际收到的字段。
例如:
@Entity
@Getter
@Setter
@NoArgsContructor
public classe SomeEntity {
@Id
private Integer id;
private String name;
private String lastName;
private LocalDate birthDate;
private Integer phoneNumber;
}
要创建您的注册表:
curl -i -X POST -H "Content-Type:application/json" -d
'{"name": "Robert", "lastName": "Downey", "bithDate": "1965-4-4", "phoneNUmber":2025550106}'
http://localhost:8080/some_entity
要替换您使用的所有记录:
curl -i -X PUT -H "Content-Type:application/json" -d
'{"name": "Robert", "lastName": "Downey", "bithDate": "1965-4-4"}'
http://localhost:8080/some_entity/{id}
在这种情况下,变量“phoneNumber”将为空。
但是,如果你试试这个:
curl -i -X PATCH -H "Content-Type:application/json" -d
'{"lastName": "Downey Jr.", "bithDate": "1965-4-15"}'
http://localhost:8080/some_entity/{id}
只会更新“lastName”和“birthDate”。
这很棒,因为您不必担心。
您可以在此 documentation 中看到更多相关信息.搜索词“补丁”,你可以找到一些例子。
如果您需要进行一些验证,例如:名称至少需要三个字。你可以像这样放置一个 EventHandler:
@Component
@RepositoryEventHandler
public class SomeEntityHandler {
@Autowired
private SomeEntityService someEntityService;
@HandleBeforeCreate
@HandleBeforeSave
public void save(SomeEntity someEntity) {
someEntity.verifyStringSize(someEntity.name);
}
}
然后您可以抛出异常,或者将所有字符串更改为大写字符串,或者您想要的任何其他内容。
关于hibernate - 在 REST 中通过部分更新实现 PATCH 方法的官方方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48824813/