0

I have this class;

public class A {
    @NotNull @Valid
    private B field;
}

When I wish to test validation of this class, I do not want it to cascade, I only wish to test @NotNull, and do not want it to cascade validation down to class B due to @Valid.

I have been using;

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<A>> validationResult = validator.validate(buildA());

But it cascades down to validation of B, how can I stop validation cascading without modifying the bean? I wish to isolate the validation of class A

buræquete
  • 14,226
  • 4
  • 44
  • 89

2 Answers2

0

There is a very good link on it, it will clear your queries: Here you will find how to limit the validation in object graphs. http://beanvalidation.org/1.0/spec/#constraintdeclarationvalidationprocess-validationroutine-graphvalidation

This recursive validation is actually due to @Valid annotation, Actually, according to the specification, adding @Valid is exactly for this usecase. From the JSR 303 specification:

In addition to supporting instance validation, validation of graphs of object is also supported. The result of a graph validation is returned as a unified set of constraint violations. Consider the situation where bean X contains a field of type Y. By annotating field Y with the @Valid annotation, the Validator will validate Y (and its properties) when X is validated.

...

The @Valid annotation is applied recursively. SO @Valid is basically for this purpose only.

Please see below answers:

Conditionally prevent cascading validation automatically cascade beans-validation recursively, @Valid annotation

Community
  • 1
  • 1
pbajpai
  • 1,303
  • 1
  • 9
  • 24
  • I know these, what I was looking is a configuration for the `Validator` I am creating to ignore this `@Valid` & stop cascading only for this validator. – buræquete Jun 24 '16 at 04:02
0

If you can modify the entity, you can try working with groups, but if not you can either use Validator.validateProperty() to just validate the property. Otherwise you could add some XML configuration overriding the annotations. Whether any of this would help you, depends on your use case and how you integrate with Bean Validation.

buræquete
  • 14,226
  • 4
  • 44
  • 89
Hardy
  • 18,659
  • 3
  • 49
  • 65