Patterncore
Data access object
Also called DAO, data access object pattern, DAO pattern.
A data access object puts all access to one kind of stored data behind an interface of persistence operations, so that business code does not depend on the storage.
- Family
- architectural
- Intent
- Abstract and encapsulate all access to the data source behind an interface.
- Also called
- DAO
Intent
The Core J2EE pattern states the solution in one line: "Use a Data Access Object (DAO) to abstract and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data."1 There is usually one DAO for each kind of stored data, such as players or orders. Its interface has the persistence operations, such as insert, find, update and delete, and the business code uses only that interface.
Problem
"Access to data varies depending on the source of the data."1 A relational database, a flat file, a directory service and a remote system each have a different interface, and two database products differ in their SQL. When the business code calls the storage interface directly, the business rules and the details of the storage are in the same functions. The pattern names the cost: "Portability of the components is directly affected when specific access mechanisms and APIs are included in the components."1 A change of storage, or a change of the table layout, then means a change in each place of the business code that reads or writes the data.
Solution
The participants are:1
- Business object. The client that needs the data. It knows only the DAO interface.
- Data access object. The interface and its implementation. The implementation holds all the code for one data source: the connection, the queries, and the conversion between the stored form and objects.
- Data source. The storage: a database, a file, a directory or another system.
- Transfer object. "This represents a Transfer Object used as a data carrier."1 The DAO returns transfer objects and takes them as arguments, so the client never sees the rows, the result sets or the file format.
PlayerService ----uses----> PlayerDao (interface)
(business object) insert, find, find_by_country, update, delete
^ ^
| |
SqlitePlayerDao TextPlayerDao
| |
database flat file
both return Player objects (transfer objects)
The Core J2EE text adds a strategy for the creation of DAOs: a factory method gives the DAO for each kind of data, and an abstract factory gives a family of DAOs for each kind of storage.1 Then one line of configuration chooses the storage. This is the Factory Method pattern and the Abstract Factory pattern; in current code, Dependency injection often does the same work.
The following program has a DAO for SQLite. All the SQL is in the DAO, and the caller gets Player objects back.
import sqlite3
from dataclasses import dataclass
@dataclass
class Player:
id: int
name: str
country: str
class SqlitePlayerDao:
# All the SQL for players is here. The caller gets Player objects back.
def __init__(self, db):
self.db = db
db.execute("create table player (id integer primary key, name text, nation text)")
def insert(self, p):
self.db.execute("insert into player values (?, ?, ?)", (p.id, p.name, p.country))
def find_by_country(self, country):
rows = self.db.execute("select id, name, nation from player where nation = ? order by id", (country,))
return [Player(*r) for r in rows]
dao = SqlitePlayerDao(sqlite3.connect(":memory:"))
dao.insert(Player(1, "Ann", "NZ"))
dao.insert(Player(2, "Bo", "AU"))
print(dao.find_by_country("NZ"))
[Player(id=1, name='Ann', country='NZ')]
Example
Each example file has a transfer object Player, a DAO interface with six operations, and two implementations of it. MemoryPlayerDao keeps a map from key to record. TextPlayerDao keeps a list of lines in the form id;name;country, as a flat file would. A factory function gives the DAO for a name, and a business object, PlayerService, moves a player to another country with only the interface. The program runs the same steps with each DAO: it inserts three players, finds one, moves one, finds the players of two countries, and deletes one. The output is the same for both DAOs. At the end, the program prints the lines in the text store, a format that the business code never saw.
from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass
class Player:
# The transfer object: plain data that goes in and out of the DAO.
id: int
name: str
country: str
class PlayerDao(ABC):
# The interface that the business code knows. It names no storage.
@abstractmethod
def insert(self, p): ...
@abstractmethod
def find(self, id): ...
@abstractmethod
def find_by_country(self, country): ...
@abstractmethod
def find_all(self): ...
@abstractmethod
def update(self, p): ...
@abstractmethod
def delete(self, id): ...
class MemoryPlayerDao(PlayerDao):
# The data source is a map from key to record.
def __init__(self):
self.rows = {}
def insert(self, p):
self.rows[p.id] = (p.name, p.country)
def find(self, id):
name, country = self.rows[id]
return Player(id, name, country)
def find_by_country(self, country):
return [self.find(id) for id in sorted(self.rows) if self.rows[id][1] == country]
def find_all(self):
return [self.find(id) for id in sorted(self.rows)]
def update(self, p):
self.rows[p.id] = (p.name, p.country)
def delete(self, id):
del self.rows[id]
class TextPlayerDao(PlayerDao):
# The data source is a flat file: one line "id;name;country" for each player.
def __init__(self):
self.lines = []
def _parse(self, line):
id, name, country = line.split(";")
return Player(int(id), name, country)
def _index(self, id):
return next(i for i, line in enumerate(self.lines) if self._parse(line).id == id)
def insert(self, p):
self.lines.append(f"{p.id};{p.name};{p.country}")
def find(self, id):
return self._parse(self.lines[self._index(id)])
def find_by_country(self, country):
return [p for p in self.find_all() if p.country == country]
def find_all(self):
return sorted((self._parse(line) for line in self.lines), key=lambda p: p.id)
def update(self, p):
self.lines[self._index(p.id)] = f"{p.id};{p.name};{p.country}"
def delete(self, id):
del self.lines[self._index(id)]
def dao_factory(kind):
# The one place that knows which storage the program uses.
return {"memory": MemoryPlayerDao, "text": TextPlayerDao}[kind]()
class PlayerService:
# The business object. It uses only the DAO interface.
def __init__(self, dao):
self.dao = dao
def transfer(self, id, country):
p = self.dao.find(id)
p.country = country
self.dao.update(p)
def names(players):
return " | ".join(f"{p.name} {p.country}" for p in players)
daos = {}
for kind in ["memory", "text"]:
dao = daos[kind] = dao_factory(kind)
service = PlayerService(dao)
print("dao:", type(dao).__name__)
for p in [Player(1, "Ann", "NZ"), Player(2, "Bo", "NZ"), Player(3, "Cy", "GB")]:
dao.insert(p)
print("all:", names(dao.find_all()))
print("find 1:", names([dao.find(1)]))
service.transfer(1, "AU")
print("from NZ:", names(dao.find_by_country("NZ")))
print("from AU:", names(dao.find_by_country("AU")))
dao.delete(3)
print("all:", names(dao.find_all()))
# The business code never saw this format; only TextPlayerDao knows it.
print("lines in the text store:", " | ".join(daos["text"].lines))
dao: MemoryPlayerDao
all: Ann NZ | Bo NZ | Cy GB
find 1: Ann NZ
from NZ: Bo NZ
from AU: Ann AU
all: Ann AU | Bo NZ
dao: TextPlayerDao
all: Ann NZ | Bo NZ | Cy GB
find 1: Ann NZ
from NZ: Bo NZ
from AU: Ann AU
all: Ann AU | Bo NZ
lines in the text store: 1;Ann;AU | 2;Bo;NZ
- Verdict: idiom.
PlayerDaois an abstract base class, so a DAO that leaves out a method cannot be created. The transfer object is a dataclass. - The two DAOs keep the data in different forms, a map of records and a list of text lines, and both give back
Playerobjects. A DAO for SQLite, as in the Solution section, has the same methods. dao_factoryis the only code that names a class of DAO.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Main {
// The transfer object: plain data that goes in and out of the DAO.
static class Player {
final int id;
final String name;
String country;
Player(int id, String name, String country) {
this.id = id;
this.name = name;
this.country = country;
}
}
// The interface that the business code knows. It names no storage.
interface PlayerDao {
void insert(Player p);
Player find(int id);
List<Player> findByCountry(String country);
List<Player> findAll();
void update(Player p);
void delete(int id);
}
// The data source is a map from key to record.
static class MemoryPlayerDao implements PlayerDao {
private final Map<Integer, String[]> rows = new TreeMap<>();
public void insert(Player p) { rows.put(p.id, new String[] {p.name, p.country}); }
public Player find(int id) {
String[] r = rows.get(id);
return new Player(id, r[0], r[1]);
}
public List<Player> findByCountry(String country) {
return findAll().stream().filter(p -> p.country.equals(country)).toList();
}
public List<Player> findAll() {
return rows.keySet().stream().map(this::find).toList();
}
public void update(Player p) { rows.put(p.id, new String[] {p.name, p.country}); }
public void delete(int id) { rows.remove(id); }
}
// The data source is a flat file: one line "id;name;country" for each player.
static class TextPlayerDao implements PlayerDao {
final List<String> lines = new ArrayList<>();
private Player parse(String line) {
String[] f = line.split(";");
return new Player(Integer.parseInt(f[0]), f[1], f[2]);
}
private int index(int id) {
for (int i = 0; i < lines.size(); i++) {
if (parse(lines.get(i)).id == id) return i;
}
throw new IllegalArgumentException("no player " + id);
}
private static String format(Player p) { return p.id + ";" + p.name + ";" + p.country; }
public void insert(Player p) { lines.add(format(p)); }
public Player find(int id) { return parse(lines.get(index(id))); }
public List<Player> findByCountry(String country) {
return findAll().stream().filter(p -> p.country.equals(country)).toList();
}
public List<Player> findAll() {
return lines.stream().map(this::parse).sorted((a, b) -> Integer.compare(a.id, b.id)).toList();
}
public void update(Player p) { lines.set(index(p.id), format(p)); }
public void delete(int id) { lines.remove(index(id)); }
}
// The one place that knows which storage the program uses.
static PlayerDao daoFactory(String kind) {
return kind.equals("memory") ? new MemoryPlayerDao() : new TextPlayerDao();
}
// The business object. It uses only the DAO interface.
static class PlayerService {
private final PlayerDao dao;
PlayerService(PlayerDao dao) { this.dao = dao; }
void transfer(int id, String country) {
Player p = dao.find(id);
p.country = country;
dao.update(p);
}
}
static String names(List<Player> players) {
return players.stream().map(p -> p.name + " " + p.country).collect(Collectors.joining(" | "));
}
public static void main(String[] args) {
Map<String, PlayerDao> daos = new TreeMap<>();
for (String kind : List.of("memory", "text")) {
PlayerDao dao = daoFactory(kind);
daos.put(kind, dao);
PlayerService service = new PlayerService(dao);
System.out.println("dao: " + dao.getClass().getSimpleName());
for (Player p : List.of(new Player(1, "Ann", "NZ"), new Player(2, "Bo", "NZ"), new Player(3, "Cy", "GB"))) {
dao.insert(p);
}
System.out.println("all: " + names(dao.findAll()));
System.out.println("find 1: " + names(List.of(dao.find(1))));
service.transfer(1, "AU");
System.out.println("from NZ: " + names(dao.findByCountry("NZ")));
System.out.println("from AU: " + names(dao.findByCountry("AU")));
dao.delete(3);
System.out.println("all: " + names(dao.findAll()));
}
// The business code never saw this format; only TextPlayerDao knows it.
TextPlayerDao text = (TextPlayerDao) daos.get("text");
System.out.println("lines in the text store: " + String.join(" | ", text.lines));
}
}
dao: MemoryPlayerDao
all: Ann NZ | Bo NZ | Cy GB
find 1: Ann NZ
from NZ: Bo NZ
from AU: Ann AU
all: Ann AU | Bo NZ
dao: TextPlayerDao
all: Ann NZ | Bo NZ | Cy GB
find 1: Ann NZ
from NZ: Bo NZ
from AU: Ann AU
all: Ann AU | Bo NZ
lines in the text store: 1;Ann;AU | 2;Bo;NZ
- Verdict: idiom.
PlayerDaois a Java interface, as in the Core J2EE pattern, and the business object holds a reference of the interface type. - In real code, the transfer object is often a record. Here
Playeris a class with a mutablecountry, becausePlayerServicechanges it before the update. - Spring and Jakarta EE applications usually get the DAO by dependency injection and not from a factory method.
// The transfer object: plain data that goes in and out of the DAO.
class Player {
constructor(id, name, country) {
Object.assign(this, { id, name, country });
}
}
// JavaScript has no interfaces. The interface of the DAO is the set of
// methods below, and both classes have all of them:
// insert(p), find(id), findByCountry(country), findAll(), update(p), delete(id)
// The data source is a map from key to record.
class MemoryPlayerDao {
constructor() {
this.rows = new Map();
}
insert(p) {
this.rows.set(p.id, [p.name, p.country]);
}
find(id) {
const [name, country] = this.rows.get(id);
return new Player(id, name, country);
}
findByCountry(country) {
return this.findAll().filter((p) => p.country === country);
}
findAll() {
return [...this.rows.keys()].sort((a, b) => a - b).map((id) => this.find(id));
}
update(p) {
this.rows.set(p.id, [p.name, p.country]);
}
delete(id) {
this.rows.delete(id);
}
}
// The data source is a flat file: one line "id;name;country" for each player.
class TextPlayerDao {
constructor() {
this.lines = [];
}
parse(line) {
const [id, name, country] = line.split(";");
return new Player(Number(id), name, country);
}
index(id) {
return this.lines.findIndex((line) => this.parse(line).id === id);
}
insert(p) {
this.lines.push(`${p.id};${p.name};${p.country}`);
}
find(id) {
return this.parse(this.lines[this.index(id)]);
}
findByCountry(country) {
return this.findAll().filter((p) => p.country === country);
}
findAll() {
return this.lines.map((line) => this.parse(line)).sort((a, b) => a.id - b.id);
}
update(p) {
this.lines[this.index(p.id)] = `${p.id};${p.name};${p.country}`;
}
delete(id) {
this.lines.splice(this.index(id), 1);
}
}
// The one place that knows which storage the program uses.
function daoFactory(kind) {
return kind === "memory" ? new MemoryPlayerDao() : new TextPlayerDao();
}
// The business object. It uses only the DAO interface.
class PlayerService {
constructor(dao) {
this.dao = dao;
}
transfer(id, country) {
const p = this.dao.find(id);
p.country = country;
this.dao.update(p);
}
}
const names = (players) => players.map((p) => `${p.name} ${p.country}`).join(" | ");
const daos = {};
for (const kind of ["memory", "text"]) {
const dao = (daos[kind] = daoFactory(kind));
const service = new PlayerService(dao);
console.log("dao:", dao.constructor.name);
for (const p of [new Player(1, "Ann", "NZ"), new Player(2, "Bo", "NZ"), new Player(3, "Cy", "GB")]) {
dao.insert(p);
}
console.log("all:", names(dao.findAll()));
console.log("find 1:", names([dao.find(1)]));
service.transfer(1, "AU");
console.log("from NZ:", names(dao.findByCountry("NZ")));
console.log("from AU:", names(dao.findByCountry("AU")));
dao.delete(3);
console.log("all:", names(dao.findAll()));
}
// The business code never saw this format; only TextPlayerDao knows it.
console.log("lines in the text store:", daos.text.lines.join(" | "));
dao: MemoryPlayerDao
all: Ann NZ | Bo NZ | Cy GB
find 1: Ann NZ
from NZ: Bo NZ
from AU: Ann AU
all: Ann AU | Bo NZ
dao: TextPlayerDao
all: Ann NZ | Bo NZ | Cy GB
find 1: Ann NZ
from NZ: Bo NZ
from AU: Ann AU
all: Ann AU | Bo NZ
lines in the text store: 1;Ann;AU | 2;Bo;NZ
- Verdict: idiom. JavaScript has no interfaces, so the DAO interface is a set of method names that both classes have. A TypeScript version would declare it as an
interface. daoFactoryis the only code that names a class of DAO, andPlayerServicegets the DAO in its constructor.
package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
// Player is the transfer object: plain data that goes in and out of the DAO.
type Player struct {
ID int
Name string
Country string
}
// PlayerDao is the interface that the business code knows. It names no storage.
type PlayerDao interface {
Insert(p Player)
Find(id int) Player
FindByCountry(country string) []Player
FindAll() []Player
Update(p Player)
Delete(id int)
}
// MemoryPlayerDao keeps the data in a map from key to record.
type MemoryPlayerDao struct {
rows map[int][2]string
}
func (d *MemoryPlayerDao) Insert(p Player) { d.rows[p.ID] = [2]string{p.Name, p.Country} }
func (d *MemoryPlayerDao) Update(p Player) { d.rows[p.ID] = [2]string{p.Name, p.Country} }
func (d *MemoryPlayerDao) Delete(id int) { delete(d.rows, id) }
func (d *MemoryPlayerDao) Find(id int) Player {
r := d.rows[id]
return Player{id, r[0], r[1]}
}
func (d *MemoryPlayerDao) FindAll() []Player {
var ids []int
for id := range d.rows {
ids = append(ids, id)
}
sort.Ints(ids)
var out []Player
for _, id := range ids {
out = append(out, d.Find(id))
}
return out
}
func (d *MemoryPlayerDao) FindByCountry(country string) []Player {
return byCountry(d.FindAll(), country)
}
// TextPlayerDao keeps the data as a flat file: one line "id;name;country" for each player.
type TextPlayerDao struct {
lines []string
}
func parse(line string) Player {
f := strings.Split(line, ";")
id, _ := strconv.Atoi(f[0])
return Player{id, f[1], f[2]}
}
func format(p Player) string { return fmt.Sprintf("%d;%s;%s", p.ID, p.Name, p.Country) }
func (d *TextPlayerDao) index(id int) int {
for i, line := range d.lines {
if parse(line).ID == id {
return i
}
}
panic("no player " + strconv.Itoa(id))
}
func (d *TextPlayerDao) Insert(p Player) { d.lines = append(d.lines, format(p)) }
func (d *TextPlayerDao) Find(id int) Player { return parse(d.lines[d.index(id)]) }
func (d *TextPlayerDao) Update(p Player) { d.lines[d.index(p.ID)] = format(p) }
func (d *TextPlayerDao) Delete(id int) {
i := d.index(id)
d.lines = append(d.lines[:i], d.lines[i+1:]...)
}
func (d *TextPlayerDao) FindAll() []Player {
var out []Player
for _, line := range d.lines {
out = append(out, parse(line))
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
func (d *TextPlayerDao) FindByCountry(country string) []Player {
return byCountry(d.FindAll(), country)
}
func byCountry(all []Player, country string) []Player {
var out []Player
for _, p := range all {
if p.Country == country {
out = append(out, p)
}
}
return out
}
// daoFactory is the one place that knows which storage the program uses.
func daoFactory(kind string) PlayerDao {
if kind == "memory" {
return &MemoryPlayerDao{rows: map[int][2]string{}}
}
return &TextPlayerDao{}
}
// PlayerService is the business object. It uses only the DAO interface.
type PlayerService struct {
dao PlayerDao
}
func (s PlayerService) Transfer(id int, country string) {
p := s.dao.Find(id)
p.Country = country
s.dao.Update(p)
}
func names(players []Player) string {
var s []string
for _, p := range players {
s = append(s, p.Name+" "+p.Country)
}
return strings.Join(s, " | ")
}
func main() {
daos := map[string]PlayerDao{}
for _, kind := range []string{"memory", "text"} {
dao := daoFactory(kind)
daos[kind] = dao
service := PlayerService{dao}
fmt.Println("dao:", strings.TrimPrefix(fmt.Sprintf("%T", dao), "*main."))
for _, p := range []Player{{1, "Ann", "NZ"}, {2, "Bo", "NZ"}, {3, "Cy", "GB"}} {
dao.Insert(p)
}
fmt.Println("all:", names(dao.FindAll()))
fmt.Println("find 1:", names([]Player{dao.Find(1)}))
service.Transfer(1, "AU")
fmt.Println("from NZ:", names(dao.FindByCountry("NZ")))
fmt.Println("from AU:", names(dao.FindByCountry("AU")))
dao.Delete(3)
fmt.Println("all:", names(dao.FindAll()))
}
// The business code never saw this format; only TextPlayerDao knows it.
text := daos["text"].(*TextPlayerDao)
fmt.Println("lines in the text store:", strings.Join(text.lines, " | "))
}
dao: MemoryPlayerDao
all: Ann NZ | Bo NZ | Cy GB
find 1: Ann NZ
from NZ: Bo NZ
from AU: Ann AU
all: Ann AU | Bo NZ
dao: TextPlayerDao
all: Ann NZ | Bo NZ | Cy GB
find 1: Ann NZ
from NZ: Bo NZ
from AU: Ann AU
all: Ann AU | Bo NZ
lines in the text store: 1;Ann;AU | 2;Bo;NZ
- Verdict: idiom.
PlayerDaois a Go interface, and the two DAO types satisfy it with no declaration. The transfer object is a struct passed by value. - A DAO for a database would take a
*sql.DBand return anerrorwith each result; the example leaves out the errors because the data is in memory.
use std::collections::BTreeMap;
// The transfer object: plain data that goes in and out of the DAO.
#[derive(Clone)]
struct Player {
id: u32,
name: String,
country: String,
}
fn player(id: u32, name: &str, country: &str) -> Player {
Player { id, name: name.to_string(), country: country.to_string() }
}
// The interface that the business code knows. It names no storage.
trait PlayerDao {
fn name(&self) -> &'static str;
fn insert(&mut self, p: &Player);
fn find(&self, id: u32) -> Player;
fn find_all(&self) -> Vec<Player>;
fn update(&mut self, p: &Player);
fn delete(&mut self, id: u32);
fn find_by_country(&self, country: &str) -> Vec<Player> {
self.find_all().into_iter().filter(|p| p.country == country).collect()
}
}
// The data source is a map from key to record.
struct MemoryPlayerDao {
rows: BTreeMap<u32, (String, String)>,
}
impl PlayerDao for MemoryPlayerDao {
fn name(&self) -> &'static str {
"MemoryPlayerDao"
}
fn insert(&mut self, p: &Player) {
self.rows.insert(p.id, (p.name.clone(), p.country.clone()));
}
fn find(&self, id: u32) -> Player {
let (name, country) = &self.rows[&id];
player(id, name, country)
}
fn find_all(&self) -> Vec<Player> {
self.rows.keys().map(|id| self.find(*id)).collect()
}
fn update(&mut self, p: &Player) {
self.insert(p);
}
fn delete(&mut self, id: u32) {
self.rows.remove(&id);
}
}
// The data source is a flat file: one line "id;name;country" for each player.
struct TextPlayerDao {
lines: Vec<String>,
}
fn parse(line: &str) -> Player {
let f: Vec<&str> = line.split(';').collect();
player(f[0].parse().unwrap(), f[1], f[2])
}
fn format(p: &Player) -> String {
format!("{};{};{}", p.id, p.name, p.country)
}
impl TextPlayerDao {
fn index(&self, id: u32) -> usize {
self.lines.iter().position(|line| parse(line).id == id).expect("no such player")
}
}
impl PlayerDao for TextPlayerDao {
fn name(&self) -> &'static str {
"TextPlayerDao"
}
fn insert(&mut self, p: &Player) {
self.lines.push(format(p));
}
fn find(&self, id: u32) -> Player {
parse(&self.lines[self.index(id)])
}
fn find_all(&self) -> Vec<Player> {
let mut all: Vec<Player> = self.lines.iter().map(|line| parse(line)).collect();
all.sort_by_key(|p| p.id);
all
}
fn update(&mut self, p: &Player) {
let i = self.index(p.id);
self.lines[i] = format(p);
}
fn delete(&mut self, id: u32) {
let i = self.index(id);
self.lines.remove(i);
}
}
// The business object. It uses only the DAO interface.
struct PlayerService<'a> {
dao: &'a mut dyn PlayerDao,
}
impl PlayerService<'_> {
fn transfer(&mut self, id: u32, country: &str) {
let mut p = self.dao.find(id);
p.country = country.to_string();
self.dao.update(&p);
}
}
fn names(players: &[Player]) -> String {
players.iter().map(|p| format!("{} {}", p.name, p.country)).collect::<Vec<_>>().join(" | ")
}
fn run(dao: &mut dyn PlayerDao) {
println!("dao: {}", dao.name());
for p in [player(1, "Ann", "NZ"), player(2, "Bo", "NZ"), player(3, "Cy", "GB")] {
dao.insert(&p);
}
println!("all: {}", names(&dao.find_all()));
println!("find 1: {}", names(&[dao.find(1)]));
PlayerService { dao: &mut *dao }.transfer(1, "AU");
println!("from NZ: {}", names(&dao.find_by_country("NZ")));
println!("from AU: {}", names(&dao.find_by_country("AU")));
dao.delete(3);
println!("all: {}", names(&dao.find_all()));
}
fn main() {
// The choice of storage is made here, in one place.
let mut memory = MemoryPlayerDao { rows: BTreeMap::new() };
let mut text = TextPlayerDao { lines: Vec::new() };
run(&mut memory);
run(&mut text);
// The business code never saw this format; only TextPlayerDao knows it.
println!("lines in the text store: {}", text.lines.join(" | "));
}
dao: MemoryPlayerDao
all: Ann NZ | Bo NZ | Cy GB
find 1: Ann NZ
from NZ: Bo NZ
from AU: Ann AU
all: Ann AU | Bo NZ
dao: TextPlayerDao
all: Ann NZ | Bo NZ | Cy GB
find 1: Ann NZ
from NZ: Bo NZ
from AU: Ann AU
all: Ann AU | Bo NZ
lines in the text store: 1;Ann;AU | 2;Bo;NZ
- Verdict: idiom.
PlayerDaois a trait, andfind_by_countryis a default method that both DAOs share. The business code takes&mut dyn PlayerDao, so it does not know the type of the DAO. - A DAO for a database would return
Resultvalues; the example leaves out the errors because the data is in memory.
Consequences
Benefits.
- The storage is hidden. "Access is transparent because the implementation details are hidden inside the DAO."1
- The storage can change. A new database, or a change of the tables, changes the DAO and not the business code. With a factory, the new DAO is one new class and one line of configuration.
- The business code is simpler. It has no SQL and no conversion of rows, and the Core J2EE text counts this as better readability and productivity.1
- Tests can use a fake DAO. A test gives the business object a DAO in memory, so it runs with no database.
- All data access is in one layer. The DAOs of an application together form a Database access layer.
Liabilities.
A DAO that returns its rows does not hide the storage. In the following program, the SQLite DAO returns the database row, a tuple in column order, and the business code takes the third value. A second DAO returns a dictionary, so the same business code fails. A DAO must return transfer objects, which have the same form for each data source.
This code runs but gives a wrong answer on purpose.
import sqlite3
class SqlitePlayerDao:
def __init__(self):
self.db = sqlite3.connect(":memory:")
self.db.execute("create table player (id integer primary key, name text, nation text)")
self.db.execute("insert into player values (1, 'Ann', 'NZ')")
# Wrong: the DAO returns the database row, a tuple in column order,
# and not a transfer object.
def find(self, id):
return self.db.execute("select * from player where id = ?", (id,)).fetchone()
class MemoryPlayerDao:
def __init__(self):
self.rows = {1: {"id": 1, "name": "Ann", "country": "NZ"}}
def find(self, id):
return self.rows[id]
def country_of(dao, id):
# The business code knows that the country is the third column.
return dao.find(id)[2]
print(country_of(SqlitePlayerDao(), 1))
try:
print(country_of(MemoryPlayerDao(), 1))
except KeyError as e:
print("KeyError:", e)
NZ
KeyError: 2
The errors can leak too. A DAO that lets sqlite3.Error or SQLException out ties the caller to the storage again. Spring translates them: "Spring provides a convenient translation from technology-specific exceptions, such as SQLException to its own exception class hierarchy, which has DataAccessException as the root exception."2
It is one more layer. "The DAOs create an additional layer of objects between the data client and the data source that need to be designed and implemented to leverage the benefits of this pattern."1 With the factory strategy, there are also two class hierarchies to design.
A DAO for each table makes some queries hard. A query over two tables does not belong to one DAO. Either the business code calls two DAOs and joins the results in memory, which is slow, or the DAOs get a finder method for each screen. A Query Object or a DAO for each use case is the usual answer.
When not to use it
When the persistence framework already does the work. The Core J2EE text says this for container-managed entity beans: "Applications using container-managed entity beans do not need a DAO layer, since the application server transparently provides this functionality."1 An ORM session or an EntityManager is in the same place today. A DAO whose methods only call the ORM adds code and no isolation.
For small programs and scripts. A program with one table and no plan to change it does not gain from an interface and two classes.
Variants and related patterns
Generated DAOs. The Core J2EE text describes an automatic code generation strategy, with the code made from the relations between business objects and tables.1 Android Room generates the DAO class from an annotated interface.3
Generic DAO. One DAO class, with a type parameter for the entity and the key, gives the same operations for all entities, and a subclass adds the special finders.
DAO versus repository. The two are often mixed up. A DAO is close to the storage: one data source, operations in the terms of the storage, and transfer objects. A Repository pattern is close to the domain. Fowler's Repository "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects."4 A repository often uses a DAO or a Data Mapper inside. The Javadoc of Spring's @Repository annotation lets DAO classes use it, but warns that "care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so."5
Related patterns. Fowler's Table Data Gateway is close to a DAO: an object with the SQL for one table. A DAO that returns domain objects and maps them is a Data Mapper. The Core J2EE text relates the DAO to the Broker pattern, "which describes approaches for decoupling clients and servers in distributed systems."1 The DAO interface is an application of Program to an interface, not an implementation and of Separation of concerns.
Known uses
- Spring Framework: "The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies (such as JDBC, Hibernate, or JPA) in a consistent way."2 A class with the
@Repositoryannotation gets the translation of exceptions toDataAccessException.5 - Android Room: "Each DAO includes functions that offer abstract access to your app's database. At compile time, Room automatically generates implementations of the DAOs that you define."3 Each DAO is an interface or an abstract class with the
@Daoannotation. - Java EE applications: the Core J2EE catalog shows DAOs over JDBC, with a factory of DAOs for each kind of storage.1
References
- Core J2EE Patterns, Data Access Object, Context; Problem; Forces; Solution; Participants and Responsibilities; Strategies; Consequences; Related Patterns
- Spring Framework reference, DAO Support, introduction; Consistent Exception Hierarchy
- Android Developers, Access data using Room DAOs, introduction; Anatomy of a DAO
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Repository, pattern summary
- Spring Framework 6.2.12 source, spring-context/src/main/java/org/springframework/stereotype/Repository.java, Javadoc of the Repository annotation, lines 27 to 36
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag TAJHC9 Edit this page History Report an error Markdown