jasiustasiu
jasiustasiu

Reputation: 1668

How to make conditional cascade validation (Hibernate)?

I have a class similar to this:

public Foo {

  @Valid
  private Bar bar;
  private Long barId;
}

so when I validate class Foo, class Bar is validated as well. But sometimes I don't want class Bar to be validated (eg when it's not possible to correct bad values) when I validate Foo. Can I do something similar to this:

@Valid(when="barId is null")

?

Upvotes: 2

Views: 1542

Answers (1)

Maksym Demidas
Maksym Demidas

Reputation: 7817

Actually there is no support for conditions in @Valid. I think as a workaround you can try define your custom constraint @ConditionalBarValid. You can apply it on class level:

@ConditionalBarValid
public Foo {

    private Bar bar;
    private Long barId;
}

So your constraint validator will have access to entire Foo object and it will be able:

  • check if barId is null
  • get an instance of Validator and force validation for bar object

Your ConditionalBarValidator.isValid(...) implementation may looks like this :

// case when foo is not null and foo.getBarId is null
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
boolean validationResult = validator.validate(foo.getBar()).isEmpty();

Upvotes: 1

Related Questions