DAO with JPA (and service layer/EJB3-Session Beans) or not

|
| By Webner

There is a lot of discussion on internet about whether to have DAOs or not with JPA and service layer or with session beans (which is the service layer).

My personal opinion is more favored towards DAO layer and some reasons for this are following:

1. In most of the database driven projects (except the simple ones), programmers will need to do more than direct fetch/store db calls. Even if Entity relationships are well defined what about reporting data and conditional data you will have to fetch (like fetch all users having bought products above price tag $300 in last 6 weeks). Pretty soon programmers may be writing native queries (sometimes for performance reason, which is valid). If there’s no DAO layer, session beans may get heavily loaded with sql code rather than java code. If we push the sql code down to DAO layer, session beans will be much more focused on processing logic, easier to read and clean.

2. Several “db methods” may have to be reused in different parts of code. For e.g. “Netbanking payments in last 6 weeks” might be required on User History and Payment Reports both. If retrieval of this information is within a session bean method, it will not be easier to re-use this for other session beans. That method will have to be exposed as public method by session bean, which will look odd because that was not what session bean’s contract or purpose was. In stead if there’s a dedicated DAO for Transactions, any session bean can use that. In future if a new functionality also needs to access Transactions information, programmers will know they need to look at DAO layer, they do not need to search which session bean might have this method already in-built.

3. Creating an independent database access layer gives us much more flexibility to re-use that layer in other applications. We just need to build a jar of domain objects and DAO layer classes and add to classpath. And in case required, even a desktop application can call those methods without requiring a web/app server environment. On the other hand if session beans contain db calls, it will be more difficult to achieve.

There are few more reasons like testing database access code independent of app server environment, testing session beans with mock database objects etc.

In summary, there are some very good reasons to keep using DAOs.

Leave a Reply

Your email address will not be published. Required fields are marked *