DAO unchained

Most software applications today need access to databases to store and retrieve data relevant to the application. The DAO (Data Access Object) Design Pattern advocates the separation of database access logic from the other parts of the code. Though the DAO pattern is typically associated with Java EE based applications, it is applicable to most programming languages. In Java based applications, the access to the database(s) can either be achieved using basic JDBC or through ORM frameworks like iBATIS, Spring DAO, Hibernate DAO etc.

So what makes this design pattern worth talking about compared to the many other patterns?

Having a separate data layer helps keep the database logic outside of the scope of the business layer. This makes it easy to maintain all the database related changes and most importantly, the DAO layer can be independently tested using JUnits and hooked up with a continuous build. This way it is easy to keep tabs on whether the database and the code base are always in sync.

How the database calls are implemented is also restricted to the data-access layer, so if it comes to moving from say iBATIS to Hibernate, the business classes need not be touched and post the change, the JUnits will confirm if the DAO layer still works as expected.

How does this work?

Abstracting the Data Access layer is typically done using DAO classes. So taking the most stereotype example of having an EMPLOYEE table, we would have a DAO interface for operations related to this table: EmployeeDao.

There would also need to be an implementation for this interface : EmployeeDaoImpl.

If IOC is used, then the appropriate implementation can be injected into the business layer that needs to perform Employee related database transactions.

The interface can expose methods like :

createEmployee(…employee details…)

Or updateEmployeeDetails(…employee details…)

Or terminateEmpoyee(…employee details…)

How these methods talk to the database is defined only within the scope of the DAO. The business class will only call the appropriate DAO’s method to get the work done. This pattern is easy to implement and provides a structured database persistence layer.

Bharat Krishna is a Lead Consultant at Compassites Software and has worked on Java EE based projects for prominent investment banks. He has worked extensively with Spring and Hibernate and has set up Continuous Integration in many of his projects. Prior to working at Compassites he worked at Credit Suisse in Singapore. He is a product of IIT Madras. He loves karaoke singing and remixing music.