100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What is the DAO Pattern?

Learn the DAO (Data Access Object) pattern — isolating SQL and persistence code — with a Java example and DAO vs Repository comparison.

mediumQ181 of 226 in Object Oriented Programming Est. time: 5 minsLast updated:
Open Code Lab

Expected Interview Answer

The DAO (Data Access Object) pattern is a structural pattern that isolates all persistence-related code — SQL statements, connection handling, and result-set mapping — behind an object with methods like insert, update, delete, and select, so the rest of the application never touches the database API directly.

A DAO typically corresponds closely to a database table and exposes low-level, technology-aware operations (e.g. UserDao.insertUser(user), UserDao.findByEmail(email)), whereas a Repository is a higher-level, more domain-oriented abstraction that can span multiple DAOs and speaks in terms of the domain model rather than tables. In practice DAOs are often the implementation detail sitting underneath a repository: the repository defines the business-facing contract, and one or more DAOs handle the actual JDBC/SQL work. DAO predates Repository as a named pattern (it comes from early J2EE design patterns) and is most useful for isolating vendor-specific data access code so it can be swapped or mocked without touching business logic.

  • Isolates SQL/JDBC/vendor-specific code from business logic
  • Makes persistence code independently testable and mockable
  • Centralizes query and mapping logic per table/entity
  • Provides a clean seam for swapping database vendors

AI Mentor Explanation

A ground’s data-entry clerk is the only person who knows the exact paper forms and filing cabinets used to record match statistics — coaches never touch the forms directly, they just ask the clerk for "insert this score" or "look up this player’s record." The clerk’s job is purely mechanical: translate a request into the specific filing procedure. That is the DAO pattern: a dedicated object that isolates the raw, technology-specific mechanics of storing and retrieving data from everyone else who needs that data.

Step-by-Step Explanation

  1. Step 1

    Define one DAO per table/entity

    Create a DAO class scoped to a specific database table or closely related entity.

  2. Step 2

    Expose CRUD-style methods

    Provide methods like insert(), update(), delete(), findById() that map directly to SQL operations.

  3. Step 3

    Encapsulate connection and mapping logic

    JDBC connections, prepared statements, and ResultSet-to-object mapping stay entirely inside the DAO.

  4. Step 4

    Let higher layers depend on the DAO interface

    Services or repositories call the DAO without knowing SQL or vendor-specific details.

What Interviewer Expects

  • Correct definition: isolates raw persistence/SQL mechanics behind an object
  • Ability to contrast DAO with Repository when asked (lower-level vs domain-facing)
  • Awareness that DAOs are usually scoped per table/entity, not per aggregate
  • Mention of testability via mockable DAO interfaces

Common Mistakes

  • Treating DAO and Repository as exactly the same thing with no distinction
  • Letting SQL or JDBC types leak out of the DAO into business logic
  • Putting business rules inside the DAO instead of keeping it purely about persistence mechanics
  • Creating one giant DAO for the whole application instead of one per table/entity

Best Answer (HR Friendly)

The DAO pattern puts all the low-level database code — SQL statements, connections, mapping rows to objects — into a dedicated object, so the rest of the application just calls simple methods like insertUser() or findByEmail() without knowing any SQL. It is similar to Repository, but DAO tends to sit closer to the actual table and database technology, while a repository often sits above one or more DAOs and speaks in terms of the business domain.

Code Example

A basic DAO implementation
public interface UserDao {
    void insertUser(User user);
    User findByEmail(String email);
    void deleteUser(String id);
}

public class JdbcUserDao implements UserDao {
    private final DataSource dataSource;

    JdbcUserDao(DataSource dataSource) { this.dataSource = dataSource; }

    @Override
    public void insertUser(User user) {
        String sql = "INSERT INTO users (id, name, email) VALUES (?, ?, ?)";
        // PreparedStatement setup and execution hidden here
    }

    @Override
    public User findByEmail(String email) {
        String sql = "SELECT * FROM users WHERE email = ?";
        // Execute query, map ResultSet row to a User object
        return null;
    }

    @Override
    public void deleteUser(String id) {
        String sql = "DELETE FROM users WHERE id = ?";
        // Execute the delete
    }
}

Follow-up Questions

  • How does DAO differ from the Repository pattern?
  • Why is DAO often described as lower-level than Repository?
  • How would you unit test code that depends on a DAO?
  • Where did the DAO pattern originate?

MCQ Practice

1. A DAO is primarily responsible for?

DAO isolates the technical mechanics of data access — SQL, JDBC, mapping — from the rest of the application.

2. Compared to Repository, DAO is generally considered?

DAO tends to map closely to a table with technology-aware operations, while Repository is a more domain-facing abstraction.

3. The DAO pattern originated from which design pattern tradition?

DAO comes from the classic Core J2EE design patterns catalog for isolating data access code.

Flash Cards

DAO in one line?An object isolating low-level persistence code (SQL, connections, mapping) behind simple methods.

DAO vs Repository?DAO is lower-level and table-focused; Repository is higher-level and domain-focused.

Typical scope?Usually one DAO per table or closely related entity.

Where did DAO originate?The classic Core J2EE design patterns catalog.

1 / 4

Continue Learning