JavaBean Validation - Object Association validation with @Valid

[Updated: Aug 7, 2017, Created: Aug 7, 2017]

According to the Bean Validation specification, the @Valid annotation on a given object reference is used to allow cascading Validation. The associated object can itself contain cascaded references, hence it is a recursive process. This feature is also referred as 'object graph validation'.

Example

In this example, we are purposely supplying invalid values during object creation to see @Valid annotation in action.

public class ValidAnnotationExample {

    private static class DriverLicense {
        @NotNull
        @Valid
        private Driver driver;
        @Digits(integer = 7, fraction = 0)
        private int number;

        public DriverLicense(Driver driver, int number) {
            this.driver = driver;
            this.number = number;
        }
    }

    private static class Driver {
        @NotNull
        private String fullName;
        @Min(100)
        private int height;
        @Past
        @NotNull
        private Date dateOfBirth;

        public Driver(String fullName, int height, Date dateOfBirth) {
            this.dateOfBirth = dateOfBirth;
            this.fullName = fullName;
            this.height = height;
        }
    }

    public static void main(String[] args) throws ParseException {
        Driver driver = new Driver("Joseph Waters", 60,
                new Date(System.currentTimeMillis() + 100000));
        DriverLicense dl = new DriverLicense(driver, 3454343);

        Validator validator = createValidator();
        Set<ConstraintViolation<DriverLicense>> violations = validator.validate(dl);
        if (violations.size() == 0) {
            System.out.println("No violations.");
        } else {
            System.out.printf("%s violations:%n", violations.size());
            violations.stream()
                      .forEach(ValidAnnotationExample::printError);
        }
    }

    private static void printError(ConstraintViolation<?> violation) {
        System.out.println(violation.getPropertyPath()
                + " " + violation.getMessage());
    }

    public static Validator createValidator() {
        Configuration<?> config = Validation.byDefaultProvider().configure();
        ValidatorFactory factory = config.buildValidatorFactory();
        Validator validator = factory.getValidator();
        factory.close();
        return validator;
    }
}

Output

2 violations:
driver.dateOfBirth must be in the past
driver.height must be greater than or equal to 100

Let's remove @Valid annotation in above example:

Output

No violations.

Example Project

Dependencies and Technologies Used :

  • hibernate-validator 5.2.4.Final: Hibernate's Bean Validation (JSR-303) reference implementation..
  • javax.el-api 2.2.4 Expression Language API 2.2
  • javax.el 2.2.4 Expression Language 2.2 Implementation
  • JDK 1.8
  • Maven 3.3.9

Object Association Validation Example Select All Download
  • valid-annotation-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also