Advantages of a separate DAO layer
With the arrival of ORM most of operations related to DB, like managing connections, transaction management have been abstracted to a certain extent and this has led to many people believe that we can directly call the entitymanager from service layer. I agree that we hardly change persistence layer ( atleast in services, for products its very much can be a valid scenario), But then can we overlook following advantages of DAO layer (All related to DRY)?
- Exception handling at a centralized location for all DAO issues -most of time service layer just pass on the failure to client and do not take any action. DAO can logg the exception, for example hibernate exception, log the query -these all can help dig the issue, and throw a runtime exception which will keep service layer code cleaner
- What if same query is being called from multiple location -even inside same service, for example “get list of all students”. A change in in this query, lets say an additional criteria, will have to be tracked across all occurence . If there is DAO, it will be delegated there and changes wil be at single place
- A well designed DAO layer can be used across projects -for example recently I wrote a DAO for JCR queries, and most of its part as create node, create heirarchical node, delete node etc were exposed in a manner that the lib was used across project
- We might not change the DB, but may be ORM itself need to be changed -for example one of client code which needed a deployment on Google apps had to change from hibernate to JPA (Google apps support JPA but not hibernate) -having a separate DAO made life simpler
On flip side, this does introduce more layers and extra level of delegation, but I feel it’s worth it.