原文: https://howtodoinjava.com/hibernate/unexpectedtypeexception-error/

在使用 Hiberate 验证器进行 Java Bean 验证时,学习解决 Java 异常UnexpectedTypeException

1)问题

当您尝试在任何 bean 属性上使用错误的 Hiberate 验证器注解时,都会出现UnexpectedTypeException错误。 错误栈跟踪看起来像这样。

  1. 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'
  2. at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getExceptionForNullValidator(ConstraintTree.java:108)
  3. at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getInitializedConstraintValidator(ConstraintTree.java:140)
  4. at org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:55)
  5. at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:73)
  6. at org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:127)
  7. at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:120)
  8. at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:533)
  9. at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:496)
  10. at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:465)
  11. at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:430)
  12. at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:380)
  13. at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:169)
  14. at com.howtodoinjava.example.TestHibernateValidator.main(TestHibernateValidator.java:25)

例如,您收到上述错误,您尝试将@NotBlank注解放在任何非字符串类型的字段中,例如java.lang.Long类型。

  1. public class User {
  2. @NotBlank //Incorrect usage
  3. private Long id;
  4. //More fields
  5. }

阅读更多:Hiberate 验证器

2)解决方案

如问题所述,要解决此错误,您必须使用正确的注解。 在上述问题中,@NotBlank注解只能应用于任何String字段。

要验证long类型字段,请使用注解@NotNull

  1. public class User {
  2. public class User {
  3. @NotNull(message = "Please enter id")
  4. private Long id;
  5. @Size(max = 20, min = 3, message = "{user.name.invalid}")
  6. @NotEmpty(message = "Please enter name")
  7. private String name;
  8. //More fields
  9. }

将我的问题放在评论部分。

学习愉快!