# [已解决] `UnexpectedTypeException` - 找不到约束验证器

> 原文： [https://howtodoinjava.com/hibernate/unexpectedtypeexception-error/](https://howtodoinjava.com/hibernate/unexpectedtypeexception-error/)

在使用 Hiberate 验证器进行 Java Bean 验证时，学习解决 Java 异常[`UnexpectedTypeException`](https://docs.oracle.com/javaee/7/api/javax/validation/UnexpectedTypeException.html)。

## 1）问题

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

```java
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`类型。

```java
public class User {

    @NotBlank			//Incorrect usage
    private Long id;

    //More fields
 }

```

> 阅读更多：[Hiberate 验证器](https://howtodoinjava.com/hibernate/hibernate-validator-java-bean-validation/)

## 2）解决方案

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

要验证`long`类型字段，请使用注解`@NotNull`。

```java
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
 }

```

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

学习愉快！