JavaOmnibus
J2EE Data Access Object
J2EE pattern • Integration
J2EEIntegrationJava example

Data Access Object solves a specific structural problem in the design.

Encapsulate persistence logic behind a focused data-access interface.

Pattern overview

J2EE pattern

Encapsulate persistence logic behind a focused data-access interface.

Intent

Abstract and encapsulate all access to the data source behind a clean API.

Problem

Persistence code is repeated or leaks SQL and storage details into business logic.

Solution

Create DAOs or repositories that isolate data retrieval and storage concerns.

Fit and tradeoffs

FamilyJ2EE
CategoryIntegration
Best used when
  • Whenever persistence logic should be isolated from business rules.
Tradeoffs
  • Can become redundant if it is only a pass-through over an ORM abstraction.

Java example

This example is intentionally compact so the pattern shape stays easy to see.

public interface CustomerDao {
    Optional<CustomerRecord> findById(String id);
    void save(CustomerRecord customer);
}

public final class JdbcCustomerDao implements CustomerDao {
    private final DataSource dataSource;

    public Optional<CustomerRecord> findById(String id) {
        // execute SQL and map one row
        return Optional.empty();
    }

    public void save(CustomerRecord customer) {
        // execute insert/update
    }
}

Related pages

Keep exploring