Is it possible to override the class hierarchy for hibernate/javax validation? Or how to override the parameter validation by extending a class?
Using the @Valid
annotation and having setup the javax validation annotations in my class. I want to have an extended class where the validation is removed.
I found that hibernate validation loops through the entire class hierarchy, and checks for validation even in the super classes.
I use this from a Json based REST API set up with Spring MVC.
Example:
public class Parent {
protected Integer numChildren;
@NotNull(message = "NumChildren has to be set.")
@Size(min 1, max 10, message = "A partent has to have at least one kid.")
public Integer getNumChildren() {
return numChildren;
}
public void setNumChildren(Integer numChilds) {
this.numChildren = numChilds;
}
}
public class Child extends Parent {
// A child doesnt have to have kids, but can, so I want to override this parameter
// and remove the validation requirement, and make it just optional.
@Override
public Integer getNumChildren() {
return super.numChildren;
}
}
Best Regards, Markus
Bean Validation does not allow to disable/change constraints in super classes. Constraints are always combined. I guess the way to go would be via groups, eg a ParentChecks group and a ChildChecks group. Assign the constraints which are specific to parent of child to the corresponding group. You can then redefine the default group for parent to be ParentChecks,_Parent_ and the one for child to be ChildChecks, Child. That should work.