Search code examples
javabean-validationhibernate-validator

How can I set default constraints on all my properties in hibernate validator


I want to automatically put @Valid constraints on all my properties.

Example:

public class Adult extends MyBeanValidationAbstractClass{
    @Min(18)
    public Integer age;
    @NotBlank
    public String name;
    public Dog dog;
    public Cat cat;
}

I want the Validator to think that all properties have the @Valid annotation.

How can this can be achieved?


Solution

  • So in you example, you want Dog and cat to be annotated with @Valid. I guess Integer and String should not be affected? I dont think that you can automate this, who else but you should know, which requirements your attributes have?

    --- Edit: just re-read ... you dont to write the annotations, you want to controll the Validator.

    You could write a custom Constraint-Annoation for your type

    @ValidAttributes
    public class MyClass {
    ...
    }
    

    and then use a custome Validator for that annotation. Then you could use reflection to iterate over all your attributes and validate them.