The question is where it is better (or in other words: where do you prefer) to put business validation logic of Jpa Entities.
Two ideas are:
- In the EntityListener that before save or update would validate the entity
- In the service that provides access to jpa persisting methods.
There are pros and cons of both.
When using approach No. 2 it is easier to test as you may just mock the jpa provider and test the validation logic. On the other hand with approach No. 1 the validation would happen at the same moment with validations like @NotNull etc.
I would love to know how do you solve validations in your projects and which is the better way to go.
Thanks.
Here’s a general thumb rule that I follow:
In other words, if you have a reference to a bean inside another, avoid putting in that @NotNull constraint. Your service layer is best used for that, for you’re catching the violation much earlier, and at a more logical point (since other business validations would assume that the beans are available).
As an example, consider the following entity (apologies for it wont compile)
The service layer in this case, is the one that should validate whether the user has a role attached or not. Verification in the pre-persist or pre-update phase is a bit too late, especially when there is a distinct service layer that has business logic, and the rest of the business logic in the domain model (sadly, I haven’t seen a good enough application with all of the logic in the domain model alone).