Data Access Object (DAO) design pattern in Java - Tutorial Example

Data Access Object or DAO design pattern is a popular design pattern to implement persistence layer of Java application. DAO pattern is based on abstraction and encapsulation design principles and shields rest of application from any change in the persistence layer e.g. change of database from Oracle to MySQL, change of persistence technology e.g. from File System to Database. For example, if you are authenticating the user using a relational database and later your company wants to use LDAP to perform authentication. If you are using DAO design pattern to access database, it would be relatively safe as you only need to make a change on Data Access Layer. DAO design pattern also keeps coupling low between different parts of an application. By using DAO design pattern your View Layer is completely independent of DAO layer and only Service layer has the dependency on it which is also abstracted by using DAO interface.

Btw, DAO or Data Access Object Pattern is not a GOF design pattern as prescribed by Gang of Four on the classic book, Design Patterns: Elements of Reusable Object-Oriented Software.  It's not one of the object oriented design pattern but something which arises from the use of Encapsulation. By keeping data access code together, away from business logic so that it can be developed, optimized and change without impacting other layers of application e.g. Model and View layer.

You can further use Generics to template your DAO layer. If you are using Spring then you can leverage JdbcTemplate for performing JDBC calls which save a lot of boilerplate coding. Using DAO pattern to access database is one of the JDBC best practices to follow.

What is Data Access Object (DAO) pattern in Java

Data access object design patter or DAO pattern in Java with ExampleIn short Data Access Object or DAO design pattern is a way to reduce coupling between Business logic and Persistence logic. Application business logic often needs domain objects which are persisted in either Database, File System or any other persistence storage. DAO pattern allows you to encapsulate code for performing CRUD operation against persistence from rest of application. Which means any change on persistence logic will not affect other layers of application which are already tested. DAO pattern enables an application to cope with any change in database provider or persistence technology.

In next section, we will What are the main benefits of using DAO design pattern in Java application. If you are a J2EE developer, you should read Real World Java EE patterns and best practices, one of the best books to learn Java EE patterns for experienced Java JEE programmers.

Good book to learn Java EE Patterns

Benefits of using DAO design pattern
DAO or Data Access Object design pattern is a good example of abstraction and encapsulation object oriented principles. It separates persistence logic is a separate layer called Data access layer which enables application to react safely to change in Persistence mechanism. For example, if you shift from File-based persistence mechanism to Database, your change will be limited to data access layer and won't impact Service layer or domain Objects. Data Access Object or DAO pattern is pretty much standard in Java application being it core Java, web application or enterprise application. Following are couple of more benefits of using DAO pattern in Java application:

1) DAO design pattern allows JUnit test to run faster as it allows to create Mock and avoid connecting to database to run tests. It improves testing because it's easy to write test with Mock objects, rather than an Integration test with the database. In the case of any issue, while running Unit test, you only need to check code and not database. Also shields with database connectivity and environment issues.

2) Since DAO pattern is based on interface, it also promotes Object oriented design principle "programming for interface than implementation" which results in flexible and quality code.

How to use DAO Pattern in Java JEE Application

Here is a nice diagram how to implement Data Access Pattern in a Java and J2EE application. You can see that your DAO classes e.g. AddressDAO, PersonDAO, and CompanyDAO are accessing database and populating data into a Contact object.

A Client Service is not directly accessing these classes instead it is accessing it via a ContactDAO interface and object are created using ContactDAOFactory class which returns the DAO implementation based on the database vendor e.g. here it is returning classes which can interact with HSQL DB. You can return classes which can interact with Oracle, SQL Server or MySQL database as well.

Data Access Object Pattern in Java

DAO design pattern Example

In the core of Data Access Object or DAO pattern is a Java interface, which defines a various method to perform CRUD operation e.g. Create, Read, Update, and Delete. Based on your application back-end technology you can create different implementation of this interface e.g. JdbcDAOImpl to connect database using JDBC, HibernateDAOImple to use hibernate or FileDAOImpl if you are using the File system for persistence. Service layer which uses this Data Access Object will use interface to interact with Data access layer. Here is how a typical DAO Interface looks like:

public interface AccountDAO{
   public boolean save(Account account);
   public boolean update(Account account);
   public boolean findByAccountNumber(int accountNumber);
   public boolean delete(Account account);


it defines various methods to perform CRUD operation. Now you can create different implementation of this AccountDAO interface e.g. JdbcAccountDAOImpl or HibernateAccountDAOImpl. Your JdbcAccountDAOImpl will use JDBC API or Spring JdbcTemplate along with SQL Queries to perform CRUD operations.

That's all on what is Data Access Object or DAO pattern in Java and what are benefits of using DAO pattern in Java application. We have also seen a simple example of How to implement Data Access Object pattern with AccountDAO interface. It's standard and one of the standard JDBC practices to use DAO pattern to create the persistent layer in Java application.

Other Java design pattern tutorials from Javarevisited blog


Mangapathi said...

Hi Paul, I am new to spring security. I read your security using LDAP and it was very helpful to me.Currently in my application I'm using DAO Authentiation provider. I need to change to LDAP. I configured as specified in your article, keeping my previous configuration as it is. Here my doubt is how to decide whether I have to use LDAP or DAO Authentication provider? Can you please help in this regard to proceed further. please provide if any example exists with you. thanks!

Javin @ print array java said...

Hi Mangapthi, it's based on requirement. Since LDAP is standard of maintaining user account and access and there are admin tools exist for that, its always a prefer choice. If you are doing any business application, almost all the time you will use LDAP in DAO layer for authentication. On the other hand using database for storing user name and password it's good for test purpose but require more tools like web app to create and maintain user accounts. Data access object or DAO pattern enable you to switch between them.

Mangapathi said...

Thanks for your quick reply Paul.
In my app as of now I am using DAO Authentication provider and there are some events like checking user password expired or not.If yes I will redirect page to change password. But here I have to redirect only if authentication is happening using DAO not by LDAP.In this case how I need to check whether my app is using LDAP or not.
For doing this is there any approach, I mean like setting some property to true while configuring LDAP in security context.
thanks in Advance. you can mail me at :

Javin @ HashMap vs HashSet said...

Hi Mangapathi, One way I can think of doing this is using a flag in ServletContext that whether you are using database or LDAP or authentication.

Mangapathi said...

Hi Paul, In my app I am loading some other properties and I added a flag to check the above condition. It was working fine. thank you for your suggestion.

Dileep Kumar said...

how i call the operation getOption

Anonymous said...

Always remember to make your DAO class name same as Table name, for example if you have Customer table than your DAO class should be called OrderDAO, similarly if you have Product table than you can name it OrderDAO. If its not possible then consider declaring a public static final String TABLE = "ORDER_XYZ", this makes easy to correlated which table a particular DAO class is connecting. Ideally you should know table name by just looking name of DAO class, but in worst case it must contain such field at top of the class.

sandeep said...

awesome explanation!

Post a Comment