如何应用hibernate验证器当数据通过post提交时,在put时省略?

jdzmm42g  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(287)

具有相同的dto对象 POST 以及 PUT 方法:

class AcmeRequest {
    private String id;
    @NotEmpty
    private String productCode;
    private String description;
}

为了 POST 我一直期待看到的请求 productCode 菲尔德,这就是我指定的原因 @NotEmpty 但是什么时候 PUT 已收到请求 productCode 应该是可选的。
有没有可能只是跳过一些 @NotEmpty 当请求是 PUT ?

jljoyd4f

jljoyd4f1#

每个hibernate验证程序注解都有一个 groups 参数。通过接口,您可以控制激活哪些验证。详见文档。
在控制器级别中,指定 groups 必须使用 @Validated 注解。
下面是我的一个演示项目的一个小例子。我曾经和你有过同样的问题。
实体:

@Entity
@Table(name = "tasks")
@Getter @Setter
public class Task
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Null(message = "You can't provide a task ID manually. ID's are automatically assigned by our internal systems.", groups = {TaskInsertValidatorGroup.class})
    @NotNull(message = "You must provide an id" , groups = TaskUpdateValidatorGroup.class)
    private Integer id;

    @NotBlank(message = "Task description cannot be empty")
    @Length(max = 255 , message = "Task description length must not exceed 255 characters")
    private String description;

    @JsonProperty("is_completed")
    @Column(name = "is_completed")
    private Boolean isCompleted = false;

    @CreationTimestamp
    @JsonProperty("created_on")
    @JsonFormat(pattern="dd-MM-yyyy HH:mm:ss")
    @Column(name = "created_on", updatable = false)
    private Timestamp creationDate;

    @UpdateTimestamp
    @JsonProperty("last_modified")
    @JsonFormat(pattern="dd-MM-yyyy HH:mm:ss")
    @Column(name = "last_modidied")
    private Timestamp lastModificationDate;

    @Override
    public boolean equals(Object o)
    {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Task task = (Task) o;
        return id.equals(task.id);
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(id);
    }
}

接口:

public interface TaskInsertValidatorGroup {}

public interface TaskUpdateValidatorGroup{}

控制器:

RestController
@RequestMapping("/api")
public class TaskRestController
{

    @Autowired
    private TaskService taskService;

    @GetMapping("/tasks/{id}")
    public ResponseEntity<?> getTask(@PathVariable Integer id)
    {
        return new ResponseEntity<>(taskService.findTask(id),HttpStatus.OK);
    }

    @GetMapping("/tasks")
    public ResponseEntity<?> getTasks()
    {
        return new ResponseEntity<>(taskService.findAllTasks(),HttpStatus.OK);
    }

    @PostMapping("/tasks")
    public ResponseEntity<?> addTask(@Validated(TaskInsertValidatorGroup.class) @RequestBody Task task)
    {
        taskService.saveTask(task);
        APISuccessResponse response = APISuccessResponse.builder()
                .info("Task added")
                .build();

        return new ResponseEntity<>(response,HttpStatus.OK);
    }

    @RequestMapping(value = "/tasks" , method = RequestMethod.PATCH)
    public ResponseEntity<?> updateTask(@Validated(TaskUpdateValidatorGroup.class) @RequestBody Task task)
    {
        taskService.updateTask(task);
        APISuccessResponse response = APISuccessResponse.builder()
                .info("Task Updated")
                .build();

        return new ResponseEntity<>(response,HttpStatus.OK);
    }

    @RequestMapping(value = "/tasks/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<?> removeTask(@PathVariable Integer id)
    {
        taskService.removeTask(id);
        APISuccessResponse response = APISuccessResponse.builder()
                .info("Task Deleted")
                .build();

        return new ResponseEntity<>(response,HttpStatus.OK);
    }

}

相关问题