Skip to content

Latest commit

Β 

History

History
52 lines (33 loc) Β· 1.92 KB

File metadata and controls

52 lines (33 loc) Β· 1.92 KB

pattern-dao-sample

A minimal demonstration of the DAO (Data Access Object) pattern in Java.

What It Demonstrates

DAO is a pattern that hides data access details behind an interface.

Business logic works against the UserRepository interface and has no knowledge of where or how data is stored β€” whether in a HashMap, ArrayList, PostgreSQL, or anything else.

The project illustrates this with a concrete example: the same UserRepository interface is implemented two ways β€” via HashMap and via ArrayList. Behavior is identical, implementation is different.

Structure

All code is in a single file: DaoArchitecture.java

DaoArchitecture.java
β”‚
β”œβ”€β”€ User                          # Model β€” record with id and name
β”œβ”€β”€ UserRepository                # DAO contract β€” findById / findAll / save / delete
β”œβ”€β”€ InMemoryMapUserRepository     # Implementation via HashMap β€” O(1) lookup by id
β”œβ”€β”€ InMemoryListUserRepository    # Implementation via ArrayList β€” sequential scan O(n)
└── DaoArchitecture               # Entry point + demo()

Key Points

Interface as contract. UserRepository defines what to do β€” not how. The calling code is written against the interface and has no idea which implementation is in use.

Two implementations β€” one behavior. InMemoryMapUserRepository uses a HashMap β€” O(1) lookup by id. InMemoryListUserRepository uses an ArrayList β€” sequential scan at O(n). From the outside, there is no difference.

Substitutability. Swapping the implementation requires changing a single line. Nothing else changes β€” that is the point of DAO.

Console Output

MAP:  Optional[User[id=1, name=jack]]
LIST: Optional[User[id=1, name=jack]]

Both implementations return the same result.

Run

./mvnw spring-boot:run

See also