1

Is it possible to turn off certain constraints / annotations per class at runtime? For instance if I wanted to turn of a @NotNull check on a firstName field, is that possible?

This would make testing to see whether a certain constraint is triggered correctly simpler, as I could turn off all the other constraints, and just check that one constraint.

2 Answers 2

1

Is it possible to turn off certain constraints / annotations per class at runtime? For instance if I wanted to turn of a @NotNull check on a firstName field, is that possible?

No it is not. Bean Validation does not define such a feature. There is an open issue in Hibernate Validator HV-98 which discusses the possibility of reloading metadata, but even there you would need to rebuild the validator factory.

You could override annotations via XML configuration and then recreate the Validator(Factory) instance using different configurations at the time, but that's probably not easy to mange.

This would make testing to see whether a certain constraint is triggered correctly simpler, as I could turn off all the other constraints, and just check that one constraint.

If it is about testing, you can use Validator.validateValue to just validate a given field. Other than that, if you validate the whole object graph and get a set of constraint violations back, you can just iterate over them and inspect the metadata. There is enough information in the metadata to verify that a specific constraints was executed and failed.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect - Validator.validateValue is exactly what I was looking for. Thanks.
0

The hibernate validation annotation are usually used together with database constraints so it does not make sense to change the behavior at runtime. However if you want to do it you can implement your own validators (by overriding existing) and do whatever you want.

3 Comments

Suppose I implement the annotation myself - How do I switch it off at runtime?
If you want only one field to be validated then you need to create something like whitelist and check the field name inside your validator against that checklist. The whitelist could be implemented as a Singleton. Getting the field name inside validator is not that straightforward, in worse case you can use payload object to pass field name to validator.
OK - Thanks - I figured it would be a non trivial exercise. I'll probably just keep the validation annotations to a minimum and perform type level validation outside of hibernate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.