Javax.validation: Get error message 'Cannot find validator for type:'

Framework: JQuery, Spring, hibernation, hibernation validator (JSR-303 Bean validation)
Platform: Windows

I am trying to define a @IdMustExist user constraint using the JSR 303-Bean Validation. The purpose of the restriction is to check if the entered identifier value exists in the linked table. I get the error message 'javax.validation.UnexpectedTypeException: for type: no validator found for it: com.mycompany.myapp.domain.package1.class1'.

If I put @IdMustExist in the definition of the Class1 field (as shown in the example below), I get the above error. But if I put the @IdMustExist constraint in the String field, I do not get the above error. My code crashes in IdMustExistValidator.java. I do not understand why Hibernate can find a Validator for the String class, but not for the Class1 domain class.

The definitions of my class are as follows.

Class2.java

@Entity
@Table
public class Class2 extends BaseEntity {
/**
 * Validation: Class1 Id must exist. 
 */ 
@ManyToOne
@JoinColumn(name="Class1Id")
@IdMustExist(entity=Class1.class)
private Class1 class1;

..

IdMustExist.java

@Required
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = IdMustExistValidator.class)
@Documented
@ReportAsSingleViolation
public @interface IdMustExist {
String message() default "{com.mycompany.myapp.domain.validation.constraints.idmustexist}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};

/**
 * The entity class that contains the id property.
 */
Class<?> entity();

/**
 * The property of the entity we want to validate for existence. Default value is "id"
 */
String idProperty() default "id";
}

IdMustExistValidator.java (note that there are errors in this class)

public class IdMustExistValidator implements ConstraintValidator<IdMustExist, Serializable> {

/**
 * Retrieve the entity class name and id property name
 */
public void initialize(IdMustExist idMustExist) {
    if (idMustExist.entity() != null) 
        entity = idMustExist.entity();
    idProperty = idMustExist.idProperty();
}

/**
 * Retrieve the entity for the given entity class and id property.
 * If the entity is available return true else false
 */
public boolean isValid(Serializable property, ConstraintValidatorContext cvContext) {
    logger.debug("Property Class = {}", property.getClass().getName());
    logger.debug("Property = {}", property);
    List resultList = commonDao.getEntityById(entity.getName(), idProperty);
    return resultList != null && resultList.size() > 0;
}

private Class<?> entity;
private String idProperty;

@Autowired
private CommonDao commonDao;
private final Logger logger = LoggerFactory.getLogger(IdMustExistValidator.class);

}

+5
source share
1 answer

Your constraint validator for checking values ​​has been declared Serializable. Maybe Class2not Serializable?

+4
source

All Articles