DAO (Data Access Object) Pattern in Java
Learn DAO Pattern in Java with JDBC, Hibernate, Spring Boot, CRUD operations, database abstraction, enterprise architecture, UML diagrams, code examples, and interview questions.
What You Will Learn
- What is DAO Pattern?
- Why DAO is Needed
- DAO Architecture
- JDBC DAO Example
- Hibernate DAO Example
- DAO vs Repository
- Enterprise Use Cases
- Benefits and Limitations
- Interview Questions
Introduction
Almost every enterprise application interacts with databases.
Examples:
Customer Data
Employee Records
Orders
Transactions
Claims
Without DAO:
public class CustomerService {
public Customer getCustomer(
Long id) {
Connection connection = ...
PreparedStatement ps = ...
ResultSet rs = ...
// Database Logic
}
}
Problems:
Database Code Mixed With Business Logic
Code Duplication
Hard Maintenance
Difficult Testing
DAO Pattern solves this problem.
What is DAO Pattern?
DAO stands for:
Data Access Object
DAO is a design pattern that separates database access logic from business logic.
Instead of:
Service
↓
Database
Use:
Service
↓
DAO
↓
Database
Purpose of DAO Pattern
Primary Goal:
Encapsulate
Database Access Logic
Real World Analogy
Think about a bank employee.
Customer requests:
Account Balance
Transaction History
Loan Details
Customer never directly accesses:
Database Server
Instead:
Customer
↓
Bank Employee
↓
Database
Bank Employee acts as DAO.
Problem Without DAO
flowchart LR
A[Service]
B[JDBC Code]
C[Database]
A --> B
B --> C
Database logic scattered everywhere.
Solution With DAO
flowchart LR
A[Service]
B[DAO]
C[Database]
A --> B
B --> C
Centralized database access.
DAO Architecture
flowchart LR
A[Controller]
B[Service]
C[DAO]
D[Database]
A --> B
B --> C
C --> D
Responsibilities Of DAO
DAO handles:
Insert
Update
Delete
Select
Database Queries
CRUD Operations
Create
Read
Update
Delete
UML Diagram
classDiagram
class CustomerDAO {
+save()
+findById()
+update()
+delete()
}
class CustomerService
CustomerService --> CustomerDAO
Customer Entity
public class Customer {
private Long id;
private String name;
private String email;
}
DAO Interface
public interface CustomerDAO {
Customer findById(Long id);
List<Customer> findAll();
void save(Customer customer);
void update(Customer customer);
void delete(Long id);
}
JDBC DAO Implementation
public class CustomerDAOImpl
implements CustomerDAO {
@Override
public Customer findById(
Long id) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
// Execute SQL
return null;
}
}
Save Example
@Override
public void save(
Customer customer) {
String sql =
"INSERT INTO CUSTOMER VALUES (?, ?)";
// Execute SQL
}
Service Layer
public class CustomerService {
private CustomerDAO customerDAO;
public CustomerService(
CustomerDAO customerDAO) {
this.customerDAO =
customerDAO;
}
public Customer getCustomer(
Long id) {
return customerDAO.findById(id);
}
}
Request Flow
flowchart LR
A[Controller]
B[Service]
C[DAO]
D[Database]
A --> B
B --> C
C --> D
Hibernate DAO Example
Instead of JDBC:
public class CustomerDAOHibernate
implements CustomerDAO {
@PersistenceContext
private EntityManager entityManager;
@Override
public Customer findById(
Long id) {
return entityManager.find(
Customer.class,
id);
}
}
Hibernate Flow
flowchart LR
A[DAO]
B[Hibernate]
C[Database]
A --> B
B --> C
Spring DAO Example
@Repository
public class CustomerDAO {
}
Spring manages DAO bean automatically.
Spring DAO Flow
flowchart LR
A[Spring Container]
B[DAO Bean]
C[Database]
A --> B
B --> C
Banking Example
Entities:
Account
Customer
Loan
Transaction
DAOs:
AccountDAO
LoanDAO
TransactionDAO
Banking Architecture
flowchart LR
A[Transfer Service]
B[AccountDAO]
C[TransactionDAO]
D[Database]
A --> B
A --> C
B --> D
C --> D
Fund Transfer Flow
flowchart LR
A[Transfer Request]
B[Transfer Service]
C[AccountDAO]
D[Database]
A --> B
B --> C
C --> D
Insurance Example
Entities:
Policy
Claim
Customer
Premium
DAOs:
PolicyDAO
ClaimDAO
Insurance Architecture
flowchart LR
A[Claim Service]
B[ClaimDAO]
C[Database]
A --> B
B --> C
DAO vs Repository
| Feature | DAO | Repository |
|---|---|---|
| Focus | Database Operations | Domain Objects |
| Abstraction | Lower | Higher |
| DDD Friendly | No | Yes |
| Spring Data JPA | Limited | Excellent |
| SQL Focus | High | Medium |
DAO Characteristics
DAO typically manages:
Tables
Rows
SQL Queries
Repository Characteristics
Repository typically manages:
Domain Objects
Aggregates
Business Entities
DAO vs Service
| DAO | Service |
|---|---|
| Data Access | Business Logic |
| SQL Queries | Validation |
| CRUD | Workflow |
| Persistence | Transactions |
Unit Testing DAO
Mock DAO:
CustomerDAO dao =
Mockito.mock(
CustomerDAO.class);
Test service independently.
Testing Flow
flowchart LR
A[Test]
B[Mock DAO]
C[Service]
A --> B
B --> C
Enterprise Examples
Banking
Account Management
Loan Processing
Transaction History
Insurance
Policy Management
Claim Processing
Retail
Order Management
Inventory Tracking
Healthcare
Patient Records
Appointment Systems
Common Technologies Using DAO
JDBC
Hibernate
MyBatis
JPA
Spring JDBC
Enterprise Architecture
flowchart LR
A[Client]
B[Controller]
C[Service]
D[DAO]
E[Database]
A --> B
B --> C
C --> D
D --> E
Benefits
✅ Separation Of Concerns
✅ Centralized Database Access
✅ Easier Maintenance
✅ Better Testability
✅ Reusable Queries
✅ Cleaner Business Logic
Limitations
❌ More Classes
❌ Additional Layer
❌ Boilerplate Code
❌ Can Be Replaced By Repository In Modern Spring Apps
When To Use
Use DAO when:
- Working With JDBC
- Legacy Applications
- Direct SQL Is Required
- Hibernate Applications
When Not To Use
Avoid when:
- Using Spring Data JPA
- Repository Pattern Already Exists
- Small Utility Applications
Interview Questions
What is DAO Pattern?
A pattern that separates database access logic from business logic.
Why Use DAO?
To centralize persistence logic.
DAO Handles?
CRUD
Queries
Database Access
DAO vs Repository?
DAO focuses on database operations.
Repository focuses on domain objects.
Spring Annotation?
@Repository
Main Benefit?
Cleaner separation between service layer and database layer.
Real Enterprise Example
Imagine a Fund Transfer Service:
TransferService
↓
AccountDAO
↓
Database
The service focuses on:
Validation
Business Rules
Transactions
The DAO focuses on:
Read Account
Update Balance
Persist Transaction
Clear separation of responsibilities.
Key Takeaways
- DAO stands for Data Access Object.
- Separates database logic from business logic.
- Commonly used with JDBC, Hibernate, and legacy enterprise applications.
- Encapsulates CRUD operations.
- Improves maintainability and testability.
- Repository Pattern is often preferred in modern Spring Boot applications.
- DAO remains important for understanding enterprise architecture and legacy systems.