I understand that validation is required at several layers of an application. But, if the validations to be imposed are same across all the layers (which is the case most of the time), it makes sense to use a common validation framework. That is one of the goals of Hibernate Validator.
To ensure a valid state of an object, I plan to put validation inside the setters of an entity.
Also, I have put annotation constraints on the entity so that Hibernate can use them to validate an entity object before persisting it. Then, instead of writing my own validations (that essentially checks the same constraints as Hibernate annotations), why shouldn't I use a Validator instance inside setters to validate the properties. I could use validator.validateProperty()
for that.
However, my concern is of performance. Is it a costly affair to build a ValidatorFactory and get an instance of validator inside each setter? Or am I thinking too much about performance? If I don't use Validator, then I will opt for Apache Commons library for validations inside setters.
So, which is the better way to go?
You might have a look at method-level validation, which is part of Hibernate Validator since 4.2 (and will be part of the Bean Validation API with release 1.1) and allows to validate parameters values automatically upon invocation. That way you could validate setter parameters using AOP, dynamic proxies etc. depending on your architecture.
What concerns performance, you should typically create only one ValidatorFactory
for your application and cache this. Retrieving validators from the same factory is typically a cheap operation. Of course actual costs depend on the types and number of constraints, so you might run some performance analyses yourself to see whether there are any hot spots.