Multiple validators for one class

Hi, I would like to create multiple validators for one class. Use case for this scenario is that sometimes I need validate object recursively (deep validation) with all references but sometimes I need shallow validation (validate only properties of class).

I prepared ConstraintMapping for both validations and do this:

HibernateValidatorConfiguration cfg = Validation.byProvider(HibernateValidator.class).configure();

ConstraintMapping mapping1 = cfg.createConstraintMapping();
mapping1.type(Class.class). etc. // add deep mapping
cfg.addMapping(mapping1);
Validator validator1 = cfg.buildValidatorFactory().getValidator();

ConstraintMapping mapping2 = cfg.createConstraintMapping();
mapping2.type(Class.class). etc. // add shallow mapping
cfg.addMapping(mapping2);
Validator validator2 = cfg.buildValidatorFactory().getValidator();

But it ended with javax.validation.ValidationException: HV000171: Class is configured more than once via the programmatic constraint declaration API

I figured it out using multiple configurations:

HibernateValidatorConfiguration cfg1 = Validation.byProvider(HibernateValidator.class).configure();
ConstraintMapping mapping1 = cfg1.createConstraintMapping();
mapping1.type(Class.class). etc. // add deep mapping
cfg1.addMapping(mapping1);
Validator validator1 = cfg1.buildValidatorFactory().getValidator();

HibernateValidatorConfiguration cfg2 = Validation.byProvider(HibernateValidator.class).configure();
ConstraintMapping mapping1 = cfg2.createConstraintMapping();
mapping2.type(Class.class). etc. // add shallow mapping
cfg2.addMapping(mapping2);
Validator validator1 = cfg2.buildValidatorFactory().getValidator();

It works, but I have doubts about correctness of this solution. Can I cache all validator instances for whole JVM to not always create them? Are there any recommendations about this usage?

Thank you very much, Miso

Hi Miso,

I confirm that, for now, you can’t have a condition on the cascading. It’s either enabled or not. We don’t have groups as we have for constraints.

Your solution seems fine and I confirm that the Validator instances are thread safe and we recommend to only instantiate them once (well, once for each in your case).

1 Like