hibernate自定义校验Valid

时间:2022-05-21 12:00:31

步骤:

1.定义注解:

hibernate自定义校验Validhibernate自定义校验Valid
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyValidatorClass.class)
public @interface MyValidator {
    String message();

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
自定义校验注解

2.定义校验类

hibernate自定义校验Validhibernate自定义校验Valid
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * MyValidator,自定义注解
 * String 标注在String类型的字段上,传过来的值是String类型
 */
public class MyValidatorClass implements ConstraintValidator<MyValidator,String> {
    /**
     * 初始化注解时执行的
     * @param myValidator
     */
    @Override
    public void initialize(MyValidator myValidator) {

    }

    /**
     * 真正的校验逻辑
     * @param o
     * @param constraintValidatorContext
     * @return
     */
    @Override
    public boolean isValid(String o, ConstraintValidatorContext constraintValidatorContext) {
        return false;
    }
}
自定义校验逻辑

3.使用

hibernate自定义校验Valid

hibernate自定义校验Valid