This tutorial states:
"One solution is to simply perform these validations in the application's business tier prior to persisting the entities. However, this tends to lead to code duplication, or even worse forgetting to code the validation check in a certain execution branch."
Because of this, in my DAO strategy, when an insert, update or delete is performed, I first do validation to make sure the transaction will succeed and not fail due to Foreign Key Contraints, Unique Contstraints, etc.
So, no matter where the DAO is called (directly from UI, from another DAO), the validation will also be called first. There are 2 problems though.
1. Calling all the validation before executing any statements.
(Example: You have a transaction which does an insert for a parent, then inserts all its children) Wouldn't it be best if it validated that a parent could be inserted, that all its children could be inserted, then did the actual work.
This can be done manually, that transaction could say in the beginning, "validate parent, validate children, continue transaction", but it would be more elegant if this happened implicitly instead of explicity, so any time you use these in a transaction you wouldn't have to find ALL the objects used in the transaction and validate them first. Plus, if you chain transactions this becomes difficult.
I think all validation should be done before a transaction begins executing statements that modify/create rows: to reduce locking, rollbacks, burning identities. (Am I wrong? I only like to use rollback, when something exceptional happens, like a race condition. Should rollback be used as a tool for logic programming?)
2. If updating an object, only call the validation for the fields that were changed. For an update, if you have a unique constraint on a field that wasn't changed, don't check if its unique again.
Because flushing can't happen ONLY on commit, (identities need to be retrieved on the fly, etc) creating a system to validate all objects (implicitly) before a transaction starts might be impossible.
What validation strategy is most commonly used to keep validation inside a DAO's insert/update/delete? Just in the beginning, validate and if invalid, rollback() and throw ValidationException() ? I'm confused as to why this tutorial does validation onPostFlush, shouldn't validation be done before flushing?
And if validation is kept inside a DAO, how do you avoid unneccessary validation? Like I said in my 2nd problem.
Thanks for any help, trying to get a solid grasp around automatic validation!
|