Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to implement cross-entity-validation?

I have a project where the data-model and business-layer are located in two different modules. Of course, the bussiness-module has a dependency to the model-module. The entity-validation is implemented through java-validation-api annotations.

I'm wondering where I should implement the cross-entity-validation (business validation, where the relations between different entity types are validated). Currently I see the follwing options:

  1. Create custom javax.validation.ConstraintValidators and associated annotations. Problem is, that the validator would need access to the business-services, i.e. to retrieve related entities, but the model-module should not have a dependency to the business-module.
  2. Implement cross-entity-validation in the business-services persist/merge-methods (i.e. by using interceptors). That would be possible, but the cross-entity-validation is seperated from the entity-validation and I would like to have only one place for validation.

Which option is preferable? Are there any better suggestions?

Thanks, Sebastian

like image 903
Sebastian Bredehöft Avatar asked Jul 10 '26 14:07

Sebastian Bredehöft


1 Answers

From the ideological point of view approach 1. is better. Bean Validation is working at the level of Model (in Model-View-Controller) and it is nothing wrong if Model part talks to database. So, for instance, you can create DAOs, which can be used both by service leayer and Model validators in order to avoid code duplication.

Interceptors are also good place to validate something, but you will not be able to use full power and automaticity of Bean Validation. Probably you will need to call validate method on your model objects by hand, throw ConstraintViolationException where needed, etc. Doable, but a little bit of work. In addition some validation probably will be left in Model, so, as you've pointed out, there would be more then one place, where validation is going on.

So I would move necessary DB code to separate layer and go with option 1.

like image 89
Piotr Kochański Avatar answered Jul 14 '26 19:07

Piotr Kochański



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!