Tutorial

DAO Design Pattern

Published on August 3, 2022
author

Shubham

DAO Design Pattern

DAO stands for Data Access Object. DAO Design Pattern is used to separate the data persistence logic in a separate layer. This way, the service remains completely in dark about how the low-level operations to access the database is done. This is known as the principle of Separation of Logic.

DAO Design Pattern

With DAO design pattern, we have following components on which our design depends:

  • The model which is transferred from one layer to the other.
  • The interfaces which provides a flexible design.
  • The interface implementation which is a concrete implementation of the persistence logic.

Implementing DAO pattern

With above mentioned components, let’s try to implement the DAO pattern. We will use 3 components here:

  1. The Book model which is transferred from one layer to the other.
  2. The BookDao interface that provides a flexible design and API to implement.
  3. BookDaoImpl concrete class that is an implementation of the BookDao interface.

Let us put this logic into a diagram: DAO Pattern

DAO Pattern model Class

Now, let’s put up our model object.

package com.journaldev.model;

public class Books {

    private int isbn;
    private String bookName;

    public Books() {
    }

    public Books(int isbn, String bookName) {
        this.isbn = isbn;
        this.bookName = bookName;
    }

    // getter setter methods
}

It is a simple object with just 2 properties to keep things simple.

DAO Pattern Interface

Let’s define the interface to access the data associated with it at persistence level.

package com.journaldev.dao;

import com.journaldev.model.Books;

import java.util.List;

public interface BookDao {

    List<Books> getAllBooks();
    Books getBookByIsbn(int isbn);
    void saveBook(Books book);
    void deleteBook(Books book);
}

DAO Pattern Implementation

Next, we create a concrete class implementing the above interface.

package com.journaldev.daoimpl;

import com.journaldev.dao.BookDao;
import com.journaldev.model.Books;

import java.util.ArrayList;
import java.util.List;

public class BookDaoImpl implements BookDao {

    //list is working as a database
    private List<Books> books;

    public BookDaoImpl() {
        books = new ArrayList<>();
        books.add(new Books(1, "Java"));
        books.add(new Books(2, "Python"));
        books.add(new Books(3, "Android"));
    }

    @Override
    public List<Books> getAllBooks() {
        return books;
    }

    @Override
    public Books getBookByIsbn(int isbn) {
        return books.get(isbn);
    }

    @Override
    public void saveBook(Books book) {
        books.add(book);
    }

    @Override
    public void deleteBook(Books book) {
        books.remove(book);
    }
}

Using DAO Pattern

Finally, we put this implementation to use in our main() method:

package com.journaldev;

import com.journaldev.dao.BookDao;
import com.journaldev.daoimpl.BookDaoImpl;
import com.journaldev.model.Books;

public class AccessBook {

    public static void main(String[] args) {

        BookDao bookDao = new BookDaoImpl();

        for (Books book : bookDao.getAllBooks()) {
            System.out.println("Book ISBN : " + book.getIsbn());
        }

        //update student
        Books book = bookDao.getAllBooks().get(1);
        book.setBookName("Algorithms");
        bookDao.saveBook(book);
    }
}

Advantages of DAO pattern

There are many advantages for using DAO pattern. Let’s state some of them here:

  1. While changing a persistence mechanism, service layer doesn’t even have to know where the data comes from. For example, if you’re thinking of shifting from using MySQL to MongoDB, all changes are needed to be done in the DAO layer only.
  2. DAO pattern emphasis on the low coupling between different components of an application. So, the View layer have no dependency on DAO layer and only Service layer depends on it, even that with the interfaces and not from concrete implementation.
  3. As the persistence logic is completely separate, it is much easier to write Unit tests for individual components. For example, if you’re using JUnit and Mockito for testing frameworks, it will be easy to mock the individual components of your application.
  4. As we work with interfaces in DAO pattern, it also emphasizes the style of “work with interfaces instead of implementation” which is an excellent OOPs style of programming.

DAO Pattern Conclusion

In this article, we learned how we can put DAO design pattern to use to emphasize on keeping persistence logic separate and so, our components loosely coupled. Design patterns are just based on a way of programming and so, is language and framework independent. Feel free to leave your views in comments below. Download the DAO example project from below link.

Download DAO Pattern Example Project

References: Oracle Documentation, Wikipedia.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Shubham

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 20, 2021

I was using this site to read a lot. But due to this dark theme you are runing the UX for most of the user. Please get rid of this.

- Ruchi

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    July 28, 2020

    Hello Sir I have requested you on LinkedIn I am java developer and full stack web developer on Java EE and PHP I need your help in java I would really like to get response for this

    - Aamir

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 12, 2020

      Never give up is the only secret to your dreams

      - Franklin.Ingrid

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 8, 2020

        so primary and the code style is not good.

        - yzwall

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          July 2, 2019

          Thanks for the great explanation I’ve been searching this kind of stuff. But what if we want to integrate this with mysql as in the above code you use list as database so how we can create a dao through which we can perform CRUD operation in sql . Thanks for your efforts ,

          - cs…

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            May 21, 2019

            The class name should be Book, not Books…

            - Rujhan Arora

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 6, 2019

              Thank you for the explanation :-)

              - Medy

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                March 15, 2019

                Good Explanation on Design patterns and it would be more easy to understand if shown using diagram

                - Sameer

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  March 6, 2019

                  Please correct me if I’m wrong but I’m wondering if there’s a typo in “While changing a persistence mechanism, service layer doesn’t even have to know where the data comes from. For example, if you’re thinking of shifting from using MySQL to MongoDB, all changes are needed to be done in the DAO layer only.” I think the changes are needed to be done in the Impl layer instead. Looking forward to your reply.

                  - Jane

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 19, 2018

                    DAO Design Pattern belongs to which design pattern - Structural or Behavioural DP?

                    - Hemanth Kumar

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Featured on Community

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more