Search code examples
javahibernatebean-validationdesign-by-contract

Hibernate Validator annotations not working


I just added hibernate-validator-5.1.3.Final.jar to my classpath and annotated a POJO:

public class Person {
    @NotNull
    private String name;

    // etc...
}

Then I went to test it out with a driver:

public class Driver {
    public static void main(String[] args) {
        Person p = new Person();
        p.setName(null);
    }
}

This executes without throwing any validation errors - where am I going awry?


Solution

  • You should run the validation engine to check if it is valid or not:

    public class Driver {
        public static void main(String[] args) {
            Person p = new Person();
            p.setName(null);
    
          ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
          Set<ConstraintViolation<Person>> constraints = factory.getValidator().validate(p);
            // constraint will have the results of validation
    
        }
    }
    

    You also need to add javax.validation:validation-api to your classpath. Most of the frameworks do these validation logics behind the scene for avoiding boilerplate codes.