繁体   English   中英

Spring PATCH 请求中的部分 bean 验证

[英]Spring partial bean validation in PATCH request

我正在制作 Spring 引导应用程序。 我在那里有一个实体:

@Entity
public class Employee {
    @NotNull
    private Category category;

    // Education related fields
    @NotNull
    private Education education;
    @NotBlank
    private String eduName;
    @NotNull
    private LocalDate eduGraduationDate;

    // other fields, getters, setters ...
}

如您所见,我在那里有验证注释。 但是在我的应用程序中,我需要部分更新这些字段,例如,客户希望将Education字段与Category字段分开更新。

问题是我不能使用 PUT 请求来做到这一点,因为它会更新整个 object。 如果Category字段实际上是null ,而我只想更新Education字段,我会得到ConstraintViolationException ,因为Category字段是null 但它是null ,我希望它进一步成为null

我可以使用 PATCH 请求来执行此操作:

@PatchMapping(path = "/{id}", consumes = "application/merge-patch+json")
public ResponseEntity<Employee> patchEmployee(@PathVariable Long id, @RequestBody JsonMergePatch jsonMergePatch) throws JsonPatchException, JsonProcessingException {
    Employee employee = employeeDataService.findById(id).orElseThrow(() -> new ResourceNotFoundException("Employee not exist: id = " + id));
        
    Employee employeePatched = applyPatchToEmployee(jsonMergePatch, employee);

    return ResponseEntity.ok(employeeDataService.save(employeePatched));
}
    
private Employee applyPatchToEmployee(JsonMergePatch jsonMergePatch, Employee targetEmployee) throws JsonPatchException, JsonProcessingException {
    JsonNode patched = jsonMergePatch.apply(objectMapper.convertValue(targetEmployee, JsonNode.class));
    return objectMapper.treeToValue(patched, Employee.class);
}

但问题是:如何部分验证我的字段?

例如,如果我发送带有正文的 PATCH 请求:

{
    "education":"HIGHER",
    "eduName":"MIT",
    "eduGraduationDate":"2020-05-05"
}

如何仅验证这 3 个字段? 不是整个Employee object? 在此示例中,如上所述,我希望Category字段为null ,如果补丁中未包含它,我不想对其进行验证。

也许有一些更好的方法来部分更新实体,如果是这样 - 哪个?

您可以创建一个新的 DTO object,其中仅包含您希望为 PATCH 调用包含的字段,例如,

EmployeePatchDto

public class EmployeePatchDto {

    // Education related fields
    @NotNull
    private Education education;
    @NotBlank
    private String eduName;
    @NotNull
    private LocalDate eduGraduationDate;

    // other fields, getters, setters ...
}

但是现在您仍然必须确保在调用 API 时考虑这些验证。 此外,您可以选择在 controller 方法级别通过使用@Valid来验证您的 DTO class,

public ResponseEntity<Employee> patchEmployee(@PathVariable Long id, @Valid @RequestBody EmployeePatchDto employeeDto) throws JsonPatchException, JsonProcessingException {

我会把这个资源留给你。 读这个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM