Search code examples
javahibernatehibernate-validator

How HibernateValidator finds ConstraintValidator when validatedBy is empty?


I wonder how Hibernate finds NullValidator class which extends ConstraintValidator interface even if @Null annotation definition as follows:

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { })
public @interface Null {}

Solution

  • validatedBy only needs to be specified for custom (i.e. user-created) constraints. All the built-in constraints that are known to Hibernate are mapped automatically. See the following code, which appears in ConstraintDescriptorImpl and XmlMappingParser:

    if ( constraintHelper.isBuiltinConstraint( annotationType ) ) {
        constraintDefinitionClasses.addAll( constraintHelper.getBuiltInConstraints( annotationType ) );
    }
    else {
        Class<? extends ConstraintValidator<?, ?>>[] validatedBy = annotationType
                .getAnnotation( Constraint.class )
                .validatedBy();
        constraintDefinitionClasses.addAll( Arrays.asList( validatedBy ) );
    }
    

    ConstraintHelper has a list of all the built-in constraints, which will be found by the isBuiltinConstraint method for these annotation types.