原文: https://howtodoinjava.com/hibernate/unexpectedtypeexception-error/
在使用 Hiberate 验证器进行 Java Bean 验证时,学习解决 Java 异常UnexpectedTypeException
。
1)问题
当您尝试在任何 bean 属性上使用错误的 Hiberate 验证器注解时,都会出现UnexpectedTypeException
错误。 错误栈跟踪看起来像这样。
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)
例如,您收到上述错误,您尝试将@NotBlank
注解放在任何非字符串类型的字段中,例如java.lang.Long
类型。
public class User {
@NotBlank //Incorrect usage
private Long id;
//More fields
}
阅读更多:Hiberate 验证器
2)解决方案
如问题所述,要解决此错误,您必须使用正确的注解。 在上述问题中,@NotBlank
注解只能应用于任何String
字段。
要验证long
类型字段,请使用注解@NotNull
。
public class User {
public class User {
@NotNull(message = "Please enter id")
private Long id;
@Size(max = 20, min = 3, message = "{user.name.invalid}")
@NotEmpty(message = "Please enter name")
private String name;
//More fields
}
将我的问题放在评论部分。
学习愉快!