411

I was going through a document and I came across a term called DAO. I found out that it is a Data Access Object. Can someone please explain me what this actually is?

I know that it is some kind of an interface for accessing data from different types of sources, and in the middle of this little research of mine I bumped into a concept called data source or data source object, which confused me even further.

I really want to know what a DAO is programmatically in terms of where it is used. How it is used? Any links to pages that explain this concept from the very basic stuff is also appreciated.

uzluisf
  • 2,586
  • 1
  • 9
  • 27
Vasanth Nag K V
  • 4,860
  • 5
  • 24
  • 48

12 Answers12

520

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.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
Rami
  • 7,162
  • 1
  • 22
  • 19
  • 4
    hi rami, m really glad thayt you tried explaining me with a very simple exaple, which is what i needed. can you please explain wat you meant with 'concrete implementation' did you mean that we have to next write the definition for the methods by implementing the interface to a class.. ?? – Vasanth Nag K V Oct 03 '13 at 12:02
  • 1
    Yes that's right. Like a class called EmployeeSQLServerDAO which implements the EmployeeDAO interface by providing full implementation for its methods in a way relevant to SQL Server – Rami Oct 03 '13 at 23:46
  • 8
    so that is all a DAO is?? it is just a class that WE are writing to access the database. whenever we need a service from the database, we create an object of a DAO use it for database operations and then get rid of the DAO once we get what we want from the database. Am i right?? and may i know the Scope of this DAO concept rami?? – Vasanth Nag K V Oct 04 '13 at 06:12
  • 8
    Yes, The DAO as its name implies is for accessing/updating the underlying storage regarding a certain entity/class. So in the above example we have an employee class/entity which we use a SQL server DB table to persist. The Employee DAO will contain methods to insert/delete/update/select employee(s) – Rami Oct 04 '13 at 06:52
  • insert, update and delete will return int(no. of rows affected) instead of boolean right? – Lucky Sep 10 '16 at 07:10
  • @Lucky Yes right you can implement it that way specially if the method accepts a list to be inserted/updated/deleted but I was thinking here about a single insert/update/delete and whether it is successful or not. – Rami Sep 12 '16 at 09:18
  • @Rami Which layer is the Employee class at? Persistence layer or database layer? – user1899020 Jun 17 '17 at 03:59
  • @user1899020 persistence layer. – Rami Jun 20 '17 at 02:40
  • 1
    That makes no sense to create an interface for employee dao. No reason you'd want more than 1 implementation. – Philip Rego Dec 26 '17 at 16:47
  • 3
    @PhilipRego we can certainly have multiple implementations for example a MSSQL server implementation, and another one that uses a CSV file to be used with unit tests. – Rami Jan 02 '18 at 02:27
  • Another question is how to handle the cross table join query? Like query `users` with their `posts`? How to name the function? – Lin Du Feb 15 '19 at 09:40
  • @slideshowp2 there is no specific way to name the method/function, just use a descriptive name :) – Rami Feb 17 '19 at 23:29
  • DAO is abstract , it is sub divided into DAOimpl. – Vishwa Ratna May 09 '19 at 05:48
  • Another question that might be beyond the scope of this discussion is: as the class `Employee` gradually becomes complicated, with more attributes filled in, like `department`, `region` and so on, we might need to query this entity with these attributes as well. Then do we have to add methods like `findByDepartment` and `findByRegion`? – 赣西狠人 Feb 18 '22 at 06:28
  • @赣西狠人 I'd say yes – Rafs Feb 23 '23 at 16:27
109

What is DATA ACCESS OBJECT (DAO) -

It is a object/interface, which is used to access data from database of data storage.

WHY WE USE DAO:

To abstract the retrieval of data from a data resource such as a database.
The concept is to "separate a data resource's client interface from its data access mechanism."
 

The problem with accessing data directly is that the source of the data can change. Consider, for example, that your application is deployed in an environment that accesses an Oracle database. Then it is subsequently deployed to an environment that uses Microsoft SQL Server. If your application uses stored procedures and database-specific code (such as generating a number sequence), how do you handle that in your application? You have two options:

  • Rewrite your application to use SQL Server instead of Oracle (or add conditional code to handle the differences), or
  • Create a layer in-between your application logic and data access layers

The DAO Pattern consists of the following:

  • Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s).
  • Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism.
  • Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.

See examples

I hope this has cleared up your understanding of DAO!

mhpreiman
  • 139
  • 2
  • 4
  • 13
VedantK
  • 9,728
  • 7
  • 66
  • 71
15

DAO (Data Access Object) is a very used design pattern in enterprise applications. It basically is the module that is used to access data from every source (DBMS, XML and so on). I suggest you to read some examples, like this one:

DAO Example

Please note that there are different ways to implements the original DAO Pattern, and there are many frameworks that can simplify your work. For example, the ORM (Object Relational Mapping) frameworks like iBatis or Hibernate, are used to map the result of SQL queries to java objects.

Hope it helps, Bye!

umanganiello
  • 756
  • 4
  • 7
9

Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services. Following are the participants in Data Access Object Pattern.

Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s).

Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism.

Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.

Sample code here..

bademba
  • 237
  • 4
  • 14
babu
  • 91
  • 1
  • 1
9

Don't get confused with too many explanations. DAO: From the name itself it means Accessing Data using Object. DAO is separated from other Business Logic.

kush
  • 486
  • 4
  • 6
ArunValaven
  • 1,753
  • 2
  • 25
  • 44
8

I am going to be general and not specific to Java as DAO and ORM are used in all languages.

To understand DAO you first need to understand ORM (Object Relational Mapping). This means that if you have a table called "person" with columns "name" and "age", then you would create object-template for that table:

type Person {
name
age
}

Now with help of DAO instead of writing some specific queries, to fetch all persons, for what ever type of db you are using (which can be error-prone) instead you do:

list persons = DAO.getPersons();
...
person = DAO.getPersonWithName("John");
age = person.age;

You do not write the DAO abstraction yourself, instead it is usually part of some opensource project, depending on what language and framework you are using.

Now to the main question here. "..where it is used..". Well usually if you are writing complex business and domain specific code your life will be very difficult without DAO. Of course you do not need to use ORM and DAO provided, instead you can write your own abstraction and native queries. I have done that in the past and almost always regretted it later.

outlier229
  • 481
  • 1
  • 7
  • 18
Orhan
  • 1,395
  • 13
  • 12
5

Spring JPA DAO

For example we have some entity Group.

For this entity we create the repository GroupRepository.

public interface GroupRepository extends JpaRepository<Group, Long> {   
}

Then we need to create a service layer with which we will use this repository.

public interface Service<T, ID> {

    T save(T entity);

    void deleteById(ID id);

    List<T> findAll();

    T getOne(ID id);

    T editEntity(T entity);

    Optional<T> findById(ID id);
}

public abstract class AbstractService<T, ID, R extends JpaRepository<T, ID>> implements Service<T, ID> {

    private final R repository;

    protected AbstractService(R repository) {
        this.repository = repository;
    }

    @Override
    public T save(T entity) {
        return repository.save(entity);
    }

    @Override
    public void deleteById(ID id) {
        repository.deleteById(id);
    }

    @Override
    public List<T> findAll() {
        return repository.findAll();
    }

    @Override
    public T getOne(ID id) {
        return repository.getOne(id);
    }

    @Override
    public Optional<T> findById(ID id) {
        return repository.findById(id);
    }

    @Override
    public T editEntity(T entity) {
        return repository.saveAndFlush(entity);
    }
}

@org.springframework.stereotype.Service
public class GroupServiceImpl extends AbstractService<Group, Long, GroupRepository> {

    private final GroupRepository groupRepository;

    @Autowired
    protected GroupServiceImpl(GroupRepository repository) {
        super(repository);
        this.groupRepository = repository;
    }
}

And in the controller we use this service.

@RestController
@RequestMapping("/api")
class GroupController {

    private final Logger log = LoggerFactory.getLogger(GroupController.class);

    private final GroupServiceImpl groupService;

    @Autowired
    public GroupController(GroupServiceImpl groupService) {
        this.groupService = groupService;
    }

    @GetMapping("/groups")
    Collection<Group> groups() {
        return groupService.findAll();
    }

    @GetMapping("/group/{id}")
    ResponseEntity<?> getGroup(@PathVariable Long id) {
        Optional<Group> group = groupService.findById(id);
        return group.map(response -> ResponseEntity.ok().body(response))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @PostMapping("/group")
    ResponseEntity<Group> createGroup(@Valid @RequestBody Group group) throws URISyntaxException {
        log.info("Request to create group: {}", group);
        Group result = groupService.save(group);
        return ResponseEntity.created(new URI("/api/group/" + result.getId()))
                .body(result);
    }

    @PutMapping("/group")
    ResponseEntity<Group> updateGroup(@Valid @RequestBody Group group) {
        log.info("Request to update group: {}", group);
        Group result = groupService.save(group);
        return ResponseEntity.ok().body(result);
    }

    @DeleteMapping("/group/{id}")
    public ResponseEntity<?> deleteGroup(@PathVariable Long id) {
        log.info("Request to delete group: {}", id);
        groupService.deleteById(id);
        return ResponseEntity.ok().build();
    }    
}
Andriy
  • 1,981
  • 1
  • 12
  • 9
  • This seems to be explaining the Repository pattern and not the DAO pattern as per the original authors request. Additionally I believe that your example can be misleading as your interface should follow a Collection like approach, so some of your operations aren't suited. – BuzZin' May 18 '20 at 16:12
4

The Data Access Object manages the connection with the data source to obtain and store data.It abstracts the underlying data access implementation for the Business Object to enable transparent access to the data source. A data source could be any database such as an RDBMS, XML repository or flat file system etc.

Rohit Goyal
  • 550
  • 8
  • 9
3

Dao clases are used to reuse the jdbc logic & Dao(Data Access Object) is a design pattern. dao is a simple java class which contains JDBC logic .

Data Access Layer has proven good in separate business logic layer and persistent layer. The DAO design pattern completely hides the data access implementation from its clients

The Java Data Access Object (Java DAO) is an important component in business applications. Business applications almost always need access to data from relational or object databases and the Java platform offers many techniques for accessingthis data. The oldest and most mature technique is to use the Java Database Connectivity (JDBC)API, which provides the capability to execute SQL queries against a databaseand then fetch the results, one column at a time.

2

DAO is an act like as "Persistence Manager " in 3 tier architecture as well as DAO also design pattern as you can consult "Gang of Four" book. Your application service layer just need to call the method of DAO class without knowing hidden & internal details of DAO's method.

Yasir Shabbir Choudhary
  • 2,458
  • 2
  • 27
  • 31
1

Pojo also consider as Model class in Java where we can create getter and setter for particular variable defined in private . Remember all variables are here declared with private modifier

1

I just want to explain it in my own way with a small story that I experienced in one of my projects. First I want to explain Why DAO is important? rather than go to What is DAO? for better understanding.

Why DAO is important?
In my one project of my project, I used Client.class which contains all the basic information of our system users. Where I need client then every time I need to do an ugly query where it is needed. Then I felt that decreases the readability and made a lot of redundant boilerplate code.

Then one of my senior developers introduced a QueryUtils.class where all queries are added using public static access modifier and then I don't need to do query everywhere. Suppose when I needed activated clients then I just call -

QueryUtils.findAllActivatedClients();

In this way, I made some optimizations of my code.

But there was another problem !!!

I felt that the QueryUtils.class was growing very highly. 100+ methods were included in that class which was also very cumbersome to read and use. Because this class contains other queries of another domain models ( For example- products, categories locations, etc ).

Then the superhero Mr. CTO introduced a new solution named DAO which solved the problem finally. I felt DAO is very domain-specific. For example, he created a DAO called ClientDAO.class where all Client.class related queries are found which seems very easy for me to use and maintain. The giant QueryUtils.class was broken down into many other domain-specific DAO for example - ProductsDAO.class, CategoriesDAO.class, etc which made the code more Readable, more Maintainable, more Decoupled.

What is DAO?

It is an object or interface, which made an easy way to access data from the database without writing complex and ugly queries every time in a reusable way.

Gk Mohammad Emon
  • 6,084
  • 3
  • 42
  • 42