Joseph Downing
Joseph Downing

Reputation: 1119

Validating nested beans using a GroupSequence and applying each group all at once

I have a couple nested classes that I would like to validate a custom constraint on. However, the validator for my custom constraint requires that a field in the Child class is not null or else it will throw an NPE.

When my custom constraint and default constraints are all on the same class, I know I can use a GroupSequence to apply one set of constraints before applying the other.

The setup I have trying something similar with nested classes looks something like this:

@MyConstraint(groups = SecondPass)
@GroupSequence([Parent, SecondPass])
class Parent {
    @Valid
    Child child
}

class Child {
    @NotNull
    String cannotBeNull
}

Note that my example code is in Groovy.

With nested classes, Hibernate's ValidatorImpl seems to be trying to apply all the specified groups first to Parent and then to Child. Therefore, it tries validating MyConstraint before checking if cannotBeNull is null or not and throws an NPE if it is.

Is there a way to have the validator validate (in a single validate call) the entire object graph against one Group first before validating any constraints in later Groups in the GroupSequence?

Upvotes: 1

Views: 1516

Answers (1)

Hardy
Hardy

Reputation: 19119

I think your problem is how you use @GroupSequence here. Unfortunately, there are two uses of @GroupSequence. One is to define sequence for validation. This is when @GroupSequence is used on an interface and this interface is requested as part of the call to Validator. For example, Validator.validate(bean, MyGroupSequenceInterfaceClass.class). In this case the sequence gets applied to the whole object graph.

In your case you are using @GroupSequence to re-define the default sequence of a class. In this case if the Default group is validated for Parent, first constraints for Parent (aka Default) and then constraints for SecondPass are validated. In this scenario the default group sequence is only changed for the actual bean. In this case Parent. It does not get passed along the object graph (@Valid). The Default group is passed across the @Valid boundary.

Upvotes: 1

Related Questions