Hibernate validator UnexpectedTypeException
改了一堆代码,忘记改啥了,然后紧急上线后发现接口报了javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.NotBlank' validating type '...'. Check configuration for 'data'
。这什么鬼?没见过啊!
References
看了下,这个错误是由hibernate validator抛出来的,当你在任何属性上加了不正确的hibernate validator就会看到这个错误。比如:
Exception in thread "main" javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.NotBlank' validating type 'java.lang.Long'. Check configuration for 'id'
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getExceptionForNullValidator(ConstraintTree.java:108)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getInitializedConstraintValidator(ConstraintTree.java:140)
at org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:55)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:73)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:127)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:120)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:533)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:496)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:465)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:430)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:380)
at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:169)
at com.howtodoinjava.example.TestHibernateValidator.main(TestHibernateValidator.java:25)
例如上面的错误就是在非String属性的字段上加了@NotBlank注解,id是java.lang.Long
类型。
public class User {
@NotBlank // 错误的用法
private Long id;
// 其他字段
}
解决方法就是换上正确的注解,比如这里的java.lang.Long
类型用@NotNull
。
这里我看了下@NotBlank
的注释:
javax.validation.constraints.NotBlank
@Documented
@Constraint(validatedBy={})
@Target(value={METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(value=RUNTIME)
@Repeatable(value=List.class)
The annotated element must not be null and must contain at least one non-whitespace character. Accepts CharSequence.
Since:
2.0
Author:
Hardy Ferentschik
See Also:
Character.isWhitespace(char)
描述说的是Accepts CharSequence
,也就是说入参只能是CharSequence
类型,也就是String
。只怪我没好好看注释。那换成@NotNull
就行了,这个注解接收的是Accepts any type
。