本文主要是介绍hibernate校验验证方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文档
简单使用
首先,在pojo添加注解,hibernate-validator提供了很多内置的注解
public class Car {@NotNullprivate String manufacturer;@NotNull@Size(min = 2, max = 14)private String licensePlate;@Min(2)private int seatCount;public Car(String manufacturer, String licencePlate, int seatCount) {this.manufacturer = manufacturer;this.licensePlate = licencePlate;this.seatCount = seatCount;}//getters and setters ...
}
制定message(el表达式)
@Size(min = 2,max = 14,message = "The license plate '${validatedValue}' must be between {min} and {max} characters long")
spring集成
@Valid
最常见的使用方式是在controller层的bean前和@Valid注解配合使用
/*** 创建新的用户*/@POST@CacheEvict(key = "#user.username")public Response createUser(@Valid @UniqueAccount Account user) {return CommonResponse.op(() -> service.createAccount(user));}
编码暴露
public static <T> String validate(T bean) {Validator validator = Validation.byProvider(HibernateValidator.class).configure()
// .addProperty( "hibernate.validator.fail_fast", "true" ).buildValidatorFactory().getValidator();Set<ConstraintViolation<T>> validate = validator.validate(bean);List<String> listError = new ArrayList<>();if (validate.size() > 0) {validate.forEach(tConstraintViolation -> listError.add(tConstraintViolation.getMessage()));return StringUtils.join(listError, ",");}return StringUtils.EMPTY;}
自定义校验器
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE, TYPE_USE })
@Retention(RUNTIME)
@Constraint(validatedBy = CheckCaseValidator.class)
@Documented
@Repeatable(List.class)
public @interface CheckCase {String message() default "{org.hibernate.validator.referenceguide.chapter06.CheckCase." +"message}";Class<?>[] groups() default { };Class<? extends Payload>[] payload() default { };CaseMode value();@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })@Retention(RUNTIME)@Documented@interface List {CheckCase[] value();}
}
定义约束器
public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {private CaseMode caseMode;@Overridepublic void initialize(CheckCase constraintAnnotation) {this.caseMode = constraintAnnotation.value();}@Overridepublic boolean isValid(String object, ConstraintValidatorContext constraintContext) {if ( object == null ) {return true;}if ( caseMode == CaseMode.UPPER ) {return object.equals( object.toUpperCase() );}else {return object.equals( object.toLowerCase() );}}
}
在field添加注解
@NotNull@Size(min = 2, max = 14)@CheckCase(CaseMode.UPPER)private String licensePlate;
自定义工具类
public class ValidateUtil {public static <T> String validate(T bean) {Validator validator = Validation.byProvider(HibernateValidator.class).configure()
// .addProperty( "hibernate.validator.fail_fast", "true" ).buildValidatorFactory().getValidator();Set<ConstraintViolation<T>> validate = validator.validate(bean);List<String> listError = new ArrayList<>();if (validate.size() > 0) {validate.forEach(tConstraintViolation -> listError.add(tConstraintViolation.getMessage()));return StringUtils.join(listError, ",");}return StringUtils.EMPTY;}public static <T> void validateAndThrow(T bean) {String validate = validate(bean);if (StringUtils.isNotEmpty(validate)) {throw new XXXException(ErrorCodeEnum.SYS_ERROR.getCode(), validate);}}}
这篇关于hibernate校验验证方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!