Data Access Object or DAO design pattern is a popular design pattern to implement the persistence layer of Java application. DAO pattern is based on abstraction and encapsulation design principles and shields the rest of the 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 the DAO design pattern to access the database, it would be relatively safe as you only need to make a change on Data Access Layer. DAO design pattern also keeps the coupling low between different parts of an application.
By using the DAO design pattern your View Layer is completely independent of the DAO layer and only the Service layer has the dependency on it which is also abstracted by using the DAO interface.
By using the DAO design pattern your View Layer is completely independent of the DAO layer and only the Service layer has the dependency on it which is also abstracted by using the DAO interface.
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 saves a lot of boilerplate coding. Using the DAO pattern to access the database is also one of the JDBC best practices to follow.
I have used DAO Pattern in most of my projects though with different flavors. In few cases we created entity objects and provide Spring Data JPA style find and create methods but in a couple of projects we just created DAO Classes which calls the stored procedure and database interaction was encapsulated on stored procedure.
This was actually a cool design because we didn't need to change anything on Java side if we need to introduce a new business logic unless there is a change in stored procedure structure. This means we can release faster and introduce functionality quickly. In this article, I will tell you everything about DAO Pattern a Java developer needs to know from theory to practical.
What is the Data Access Object (DAO) pattern in Java?
In 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 operations against persistence from the rest of the application.
This means any change in persistence logic will not affect other layers of application that are already tested. DAO pattern enables an application to cope with any change in database provider or persistence technology.
In the next section, we will What are the main benefits of using DAO design patterns in Java applications. 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.
This means any change in persistence logic will not affect other layers of application that are already tested. DAO pattern enables an application to cope with any change in database provider or persistence technology.
In the next section, we will What are the main benefits of using DAO design patterns in Java applications. 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.
Benefits of using DAO design pattern
DAO or Data Access Object design pattern is a good example of abstraction and encapsulation of object-oriented principles. It separates persistence logic is a separate layer called the Data access layer which enables the application to react safely to change in the Persistence mechanism.
For example, if you shift from a File-based persistence mechanism to Database, your change will be limited to the data access layer and won't impact the 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 a couple of more benefits of using DAO pattern in Java applications:
For example, if you shift from a File-based persistence mechanism to Database, your change will be limited to the data access layer and won't impact the 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 a couple of more benefits of using DAO pattern in Java applications:
1.Easier to Test
DAO design pattern allows the JUnit test to run faster as it allows to create Mock and avoid connecting to the database to run tests. It improves testing because it's easy to write a test with Mock objects, rather than an Integration test with the database.
In the case of any issue, while running the Unit test, you only need to check code and not database. Also shields with database connectivity and environmental issues.
2. Best Practice
Since the DAO pattern is based on interface, it also promotes the Object-oriented design principle "programming for interface than implementation" which results in flexible and quality code.
How to use the DAO Pattern in Java JEE Application? Example
Here is a nice diagram of how to implement the Data Access Pattern in a Java and J2EE application. You can see that your DAO classes e.g. AddressDAO, PersonDAO, and CompanyDAO are accessing databases 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 that can interact with Oracle, SQL Server, or MySQL database as well.
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 implementations 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.
The 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);
}
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 a 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.
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.
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.
That's all on what is Data Access Object or DAO pattern in Java and are benefits of using the DAO pattern in Java application. We have also seen a simple example of How to implement a Data Access Object pattern with the AccountDAO interface. It's standard and one of the standard JDBC practices to use the DAO pattern to create the persistent layer in Java application.
Other Java design pattern tutorials from the Javarevisited blog
- What is a Decorator design pattern in Java with Example
- 18 Java Design Pattern Interview Questions
- What is Observer design pattern with example
- 10 Microservice Design Patterns and Principles
- 10 Example of JdbcTempalte in Java Spring
- How to use Command Design Pattern in Java
- How to use Adapter Design Pattern in Java
- How to use Composite Design Pattern in Java
- 5 Free Courses to learn Design Patterns in Java
- When to use a Factory design pattern in Java
- How to implement thread-safe Singleton in Java
- 20 design pattern interview questions in Java - Answered
P. S. - If you are serious about learning design patterns and principles, I suggest you take a look at these design pattern courses for experienced developers. This course covers both SOLID design principles like Open Closed and Liskov substitution, and all-important Object Oriented design patterns like Decorator, Observer, Chain of Responsibility, and much more.
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!
ReplyDeleteHi 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.
ReplyDeleteThanks for your quick reply Paul.
ReplyDeleteIn 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 : mangapathi.samineni@gmail.com
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.
ReplyDeleteHi 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.
ReplyDeletehow i call the operation getOption
ReplyDeleteAlways 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.
ReplyDeleteawesome explanation!
ReplyDelete