I have a huge object model with lots of nested objects and fields. I need to validate all fields of the base object. Is there a way to do that without adding @Valid
annotation to all the fields?
Sample objects:
class A { @NotNull private String id; ...}
class B { @NotNull private String id; List<A> aList; ...}
class C { @NotNull private String id; B bInstance; A aInstance; ...}
class D { @NotNull private String id; List<C> cList; ... }
...
If I need to validate and instance of D recursively, I'll have to put @Valid
in all the relevant fields in A, B, C, D.
I have a large number of objects in my object model. It's easy to miss out on putting the annotation on a field.
No, you should add all the required @Valid
annotations to your object graph.
If that's really going to be a problem, you could try to automate it using Hibernate Validator's API for dynamic constraint violation. You'd have to traverse your object model reflectively and call valid()
for each reference (plain object reference or collections/maps/arrays) you encounter.
But I'd advice against it as it adds quite some complexity and makes the solution harder to understand than when looking at plain @Valid
. annotations.