Video in progress
What is the difference between a Repository in DDD and a classic DAO?
A DAO faces the table: CRUD for every table, with methods close to SQL. A Repository faces the domain: it behaves like a collection of aggregates, exists only for roots, and its interface is written in domain language.
📖 Answer
DAO style:
interface OrderLineDao {
void insert(OrderLineRow row);
void updateQty(long lineId, int qty);
List<OrderLineRow> selectByOrderId(long orderId);
}
The service assembles the lines itself, links them itself, and calls several DAOs together. The invariant checks live in the service too.
Repository style:
public interface Orders {
Optional<Order> byId(OrderId id);
void save(Order order);
List<Order> unpaidOlderThan(Duration age);
}
Differences:
- A Repository returns and saves the whole aggregate,
Ordertogether with its lines. There is no separate repository forOrderLine. - Method names are in business language:
unpaidOlderThan, notfindByStatusAndCreatedAtBefore. - The interface sits in the domain package, and the implementation (JPA, JDBC, even in-memory) sits in infrastructure. Domain code doesn't know SQL.
Spring Data's JpaRepository is really a mix of both: it's named repository, but it has technical methods like flush, deleteAllInBatch and getReferenceById, and you can create one for any entity. If you want clean DDD, you write the domain interface separately and implement it through a Spring Data repository. In a small project that's overkill; in a large domain, injecting JpaRepository straight into services spreads technical details everywhere.
Sign up to mark studied questions and save your progress.