javadao

What is Data access object (DAO) in Java


I know that it is some kind of interface for accessing data from different types of sources. When doing research, I bumped into a concept called data source or data source object, which confused me even further.

What is a DAO programmatically, in terms of where and how it is used?


Solution

  • The Data Access Object is basically an object or an interface that provides access to an underlying database or any other persistence storage.

    That definition from: http://en.wikipedia.org/wiki/Data_access_object

    Check also the sequence diagram here: http://www.oracle.com/technetwork/java/dataaccessobject-138824.html

    Maybe a simple example can help you understand the concept:

    Let's say we have an entity to represent an employee:

    public class Employee {
    
        private int id;
        private String name;
    
    
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    
    }
    

    The employee entities will be persisted into a corresponding Employee table in a database. A simple DAO interface to handle the database operation required to manipulate an employee entity will be like:

    interface EmployeeDAO {
    
        List<Employee> findAll();
        List<Employee> findById();
        List<Employee> findByName();
        boolean insertEmployee(Employee employee);
        boolean updateEmployee(Employee employee);
        boolean deleteEmployee(Employee employee);
    
    }
    

    Next we have to provide a concrete implementation for that interface to deal with SQL server, and another to deal with flat files, etc.