hibernate validator切面校验

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package io.github.lyr2000.dissertation.enums;

/**
 * 用于 hibernate 分组校验
 * @author lyr
 * @description validator
 * @create 2021-11-21 15:22
 */
public final class V {
    /**
     * 全量更新
     */
    public interface Update{}
    public interface Create{}
    public interface Delete{}
    public interface Query{}

    /**
     * 局部更新
     */
    public interface UpdateField{}

}

切面异常处理示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

    /**
     * 参数校验异常
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ViewObject validateException(MethodArgumentNotValidException ex) {
        log.info("参数校验异常");
        String frontInfo = ex.getBindingResult()
                .getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(";"));
        //将参数校验信息反馈给前端
        return ViewObject.of(DefaultApiCode.BAD_REQUEST)
                .put(ERROR_INFO, frontInfo);
    }

    /**
     * 参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ViewObject ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        log.info("参数校验异常 constraintViolation");
        String message = e.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(";"));
        return ViewObject.of(DefaultApiCode.BAD_REQUEST)
                .put(ERROR_INFO, message);
    }

    @ExceptionHandler(org.springframework.validation.BindException.class)
    public ViewObject bindExceptionHandler(org.springframework.validation.BindException e) {
        log.info("参数校验异常 constraintViolation");
        String message = e.getFieldErrors()
                .stream()
                .map(err -> String.format("%s: %s", err.getField() , err.getDefaultMessage()))
                .collect(Collectors.joining(";"));
        return ViewObject.of(DefaultApiCode.BAD_REQUEST)
                .put(ERROR_INFO, message);
    }

controller参数校验使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Data
@Accessors(chain = true)
public class UpdateCourseDTO {

    /**
     * 课程ID
     */
    @NotNull(groups = V.Update.class)
    private Long courseId;

    /**
     * 课程名字
     */
    @NotBlank(groups = {V.Create.class},message = "课程名字不能为空")
    private String courseName;

    /**
     * 图片地址
     */
    @NotBlank(groups = {V.Create.class})
    private String courseCoverImg;


    /**
     * 课程介绍或者相关内容
     */
    @NotBlank(groups = V.Create.class)
    private String courseDescription;
}