- Chapter
- Chapter 1 — Enterprise Architecture Patterns
- Prerequisites
- Topics 1.1–1.2; Chapter 2 Topic 2.3 (aggregates)
- You will be able to
- Design repositories that give the domain collection-like access to aggregates, keep persistence technology behind the abstraction, choose between Spring Data options and custom implementations, and separate write repositories from read queries
- Covers
- Persistence abstraction; Collection-like interface
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — Spring Data Repositories
- 4A. Deep Dive — Repositories vs Read Queries
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
A Repository mediates between the domain and data-mapping layers using a collection-like interface for accessing domain objects (Fowler, Evans). To the domain, a repository looks like an in-memory set of aggregates: add, find, remove — how they are stored is hidden.

| Aspect | Repository |
|---|---|
| Defined by | The domain (interface / port) |
| Implemented by | Infrastructure (JPA, JDBC, document store, in-memory for tests) |
| Unit of storage | A whole aggregate (via its root) |
| Language | Domain terms (findOverdueFor(customer)), not SQL terms |
2Why It Exists
If domain and application code build queries, manage connections and map rows, persistence concerns spread everywhere and the domain becomes impossible to test without a database. A repository concentrates query construction and mapping in one place per aggregate, allows swapping or optimising storage (caching, read replicas, a different database), and lets unit tests use simple in-memory implementations.
3Core Concepts
3.1 Persistence abstraction
The domain declares what it needs; infrastructure decides how.
// domain package — no JPA, no Spring
public interface OrderRepository {
Optional<Order> findById(OrderId id);
Order get(OrderId id); // throws OrderNotFound
void save(Order order);
List<Order> findOpenFor(CustomerId customer);
boolean existsByCommandId(CommandId id);
}// infrastructure package — technology lives here
@Repository
class JpaOrderRepository implements OrderRepository {
private final OrderJpa jpa; // Spring Data interface
JpaOrderRepository(OrderJpa jpa) { this.jpa = jpa; }
public Optional<Order> findById(OrderId id) { return jpa.findById(id.value()); }
public Order get(OrderId id) {
return findById(id).orElseThrow(() -> new OrderNotFound(id));
}
public void save(Order order) { jpa.save(order); }
public List<Order> findOpenFor(CustomerId c) {
return jpa.findByCustomerIdAndStatusIn(c.value(), OrderStatus.OPEN_STATES);
}
public boolean existsByCommandId(CommandId id) {
return jpa.existsByCommandId(id.value());
}
}
interface OrderJpa extends JpaRepository<Order, UUID> {
List<Order> findByCustomerIdAndStatusIn(UUID customerId, Set<OrderStatus> statuses);
boolean existsByCommandId(UUID commandId);
}| What the abstraction hides | Example |
|---|---|
| Query language | JPQL, SQL, Mongo queries |
| Mapping | Entity annotations, row mappers, separate persistence models |
| Performance techniques | Fetch joins, batching, caching, read replicas |
| Storage technology | Relational, document, key-value, in-memory |
A pragmatic variant, common in Spring code, lets the domain depend directly on a Spring Data interface (interface OrderRepository extends Repository<Order, UUID>). It saves a class but ties the domain to Spring Data; choose consciously (Topic 2.4).
3.2 Collection-like interface
A repository behaves like a collection of aggregates rather than a table gateway.

| Collection-like | DAO-style (avoid in domain) |
|---|---|
save(order) — add or update the aggregate | insertOrder(row), updateOrderStatus(id, s) |
findOverdueFor(customer) | selectWhere("status = ? and due < ?") |
Returns Order aggregates with their lines | Returns OrderRow without lines |
| One per aggregate root | One per table (OrderLineDao) |

Rules that follow from collection semantics:
- No repository for non-root entities — order lines are loaded and saved through their
Order. - Save the whole aggregate — the repository handles child rows.
- Query methods named by business meaning, returning aggregates or IDs.
- No partial updates from outside (
updateStatus(id, SHIPPED)bypasses the aggregate's rules).
4How It Works Internally — Spring Data Repositories
1. At startup, Spring Data scans interfaces extending Repository.
2. For each, it creates a JDK dynamic proxy backed by SimpleJpaRepository (or JDBC equivalent).
3. Derived query methods (findByCustomerIdAndStatusIn) are parsed into queries at startup — errors fail fast.
4. @Query methods use explicit JPQL/SQL.
5. Custom fragments (OrderJpaCustom + OrderJpaCustomImpl) are merged into the proxy for hand-written logic.
6. Calls run inside the caller's transaction (service layer) or start their own read-only transaction.

Spring Data JDBC is closer to DDD repositories than JPA: it loads and saves whole aggregates, has no lazy loading and no persistence context — every save writes the full aggregate.
4ADeep Dive — Repositories vs Read Queries
Repositories are optimised for loading aggregates to change them. Screens, reports and search need different shapes — often joining several aggregates, paginating and projecting a few columns. Forcing these through repositories causes N+1 queries, huge object graphs and repository interfaces with dozens of finder methods.
| Need | Use |
|---|---|
| Load an aggregate to execute a use case | Repository |
| List of order summaries for a screen | Query service with projection (JDBC, JPQL constructor expression, Spring Data interface projection) |
| Full-text search | Search index (OpenSearch) behind a query service |
| Reporting | SQL views / read models |
public record OrderSummary(UUID id, BigDecimal total, String status, Instant placedAt) {}
interface OrderSummaries extends Repository<OrderEntity, UUID> {
@Query("""
select new com.shop.orders.read.OrderSummary(o.id, o.total, o.status, o.placedAt)
from OrderEntity o where o.customerId = :customer order by o.placedAt desc""")
List<OrderSummary> recentFor(UUID customer, Pageable page);
}This is CQRS-light: one database, separate read path. Full CQRS (Chapter 7) adds separate read stores.
5APIs / Features / Syntax
| API | Purpose |
|---|---|
Repository<T, ID> | Marker interface; declare only needed methods |
CrudRepository, ListCrudRepository | CRUD operations |
JpaRepository | Paging, flushing, batch operations (JPA-specific) |
Derived queries, @Query, @EntityGraph | Query definitions and fetch plans |
| Custom fragments | Hand-written implementation parts |
| Interface/DTO projections | Read-optimised results |
@DataJpaTest, Testcontainers | Repository tests against real databases |
6Practical Examples
6.1 In-memory repository for tests
public final class InMemoryOrderRepository implements OrderRepository {
private final Map<OrderId, Order> store = new ConcurrentHashMap<>();
public Optional<Order> findById(OrderId id) {
return Optional.ofNullable(store.get(id));
}
public Order get(OrderId id) {
return findById(id).orElseThrow(() -> new OrderNotFound(id));
}
public void save(Order o) { store.put(o.id(), o); }
public List<Order> findOpenFor(CustomerId c) {
return store.values().stream()
.filter(o -> o.customer().equals(c) && o.isOpen()).toList();
}
public boolean existsByCommandId(CommandId id) { return false; }
}Application services are unit-tested with this fake; the JPA implementation is tested separately with Testcontainers.
6.2 Avoiding N+1 in a repository
@EntityGraph(attributePaths = "lines")
Optional<Order> findWithLinesById(UUID id); // one query with join for the aggregate6.3 Removing a "status update" method
orderRepository.updateStatus(id, SHIPPED) was replaced by order.ship(tracking); repository.save(order), so shipping rules and events are always applied.
6.4 Worked example — a repository for a document store and a relational store
The same OrderRepository port was implemented twice when the team evaluated moving orders to a document database. Domain and application code did not change.
@Repository
@Profile("mongo")
class MongoOrderRepository implements OrderRepository {
private final MongoTemplate mongo;
MongoOrderRepository(MongoTemplate mongo) { this.mongo = mongo; }
public Optional<Order> findById(OrderId id) {
return Optional.ofNullable(mongo.findById(id.value(), OrderDocument.class))
.map(OrderDocument::toDomain); // whole aggregate, one document
}
public Order get(OrderId id) {
return findById(id).orElseThrow(() -> new OrderNotFound(id));
}
public void save(Order order) { mongo.save(OrderDocument.from(order)); }
public List<Order> findOpenFor(CustomerId c) {
var q = Query.query(Criteria.where("customerId").is(c.value())
.and("status").in(OrderStatus.OPEN_STATES));
return mongo.find(q, OrderDocument.class).stream()
.map(OrderDocument::toDomain).toList();
}
public boolean existsByCommandId(CommandId id) {
return mongo.exists(Query.query(Criteria.where("commandIds").is(id.value())),
OrderDocument.class);
}
}| Concern | JPA implementation | Document implementation |
|---|---|---|
| Aggregate loading | Join fetch of orders + order_lines | One document read |
| Saving | Dirty checking, multiple row updates | Replace one document |
| Concurrency | @Version column | Version field with conditional replace |
Query findOpenFor | Derived query / JPQL | Criteria query |
| Domain and service code | Unchanged | Unchanged |
A shared repository contract test (an abstract JUnit class run against both implementations with Testcontainers) proved behavioural equivalence before the switch.
7Common Problems & Mistakes
- Repositories per table instead of per aggregate.
- Partial-update methods bypassing aggregate rules.
- Screens and reports served through aggregate repositories (N+1, huge graphs).
- Leaking query types (
Specification,Pageable) deep into the domain without intention. - Finder explosion — 40 derived query methods on one interface.
- Repositories calling other repositories or services.
8Performance & Production Considerations
| Aspect | Guidance |
|---|---|
| Fetching | Load the aggregate in one or few queries (@EntityGraph, joins) |
| Batching | Enable JDBC batching for large aggregates |
| Aggregate size | Keep aggregates small; large collections belong to separate aggregates |
| Read paths | Projections for lists; don't hydrate aggregates for screens |
| Testing | Testcontainers with the production database engine |
Watch repositories in production with query-level metrics, because their problems are usually invisible in code review. Enable Hibernate statistics or a datasource proxy in test and staging environments to count queries per request, and add tests that assert the query count for critical use cases so N+1 regressions are caught early. Set hibernate.jdbc.batch_size and enable ordered inserts and updates when aggregates have many children, and use @Version for optimistic locking so concurrent changes fail cleanly instead of overwriting each other. Keep transactions short: load, change and save the aggregate, then hand slow work to events processed after commit. Export HikariCP pool metrics and slow-query logs through Micrometer, and alert on connection wait time, the first sign of an overloaded persistence layer.
9Architecture & Design Considerations
- Define repository interfaces in the domain, implementations in infrastructure.
- Keep one repository per aggregate root; small aggregates make repositories simple.
- Separate write repositories from read queries early.
- Hide storage choices so that caching, sharding or a new database can be introduced behind the interface.
10Interview Questions & Answers
What is a Repository?
A Repository is a domain-facing abstraction that gives code collection-like access to aggregates while hiding how they are stored. The domain defines the interface in its own language, for example get(OrderId), save(Order) and findOpenFor(CustomerId), and infrastructure implements it with JPA, JDBC, a document store or an in-memory map for tests. Callers treat it as a set of whole aggregates they can add to, look up and remove from; queries, mapping, fetching strategies and the storage technology stay behind the interface. This concentrates persistence logic in one place per aggregate, keeps application services free of SQL and connections, and lets the domain be unit-tested without a database.
How many repositories should an aggregate have?
One, and only for the aggregate root. An aggregate is a consistency boundary, so its child entities, such as the lines of an order, are loaded, changed and saved through the root, never through a repository of their own. OrderRepository.save(order) persists the order and its lines together, and the order enforces invariants such as a maximum number of lines or a credit limit on the total. A separate OrderLineRepository would let code bypass those rules and update lines without the order knowing. If you find you need to load a child independently and frequently, that is a sign the child may really be its own aggregate, with its own identity and repository.
What is the difference between a repository and a DAO?
A repository is a domain concept: it speaks the domain's language, works with whole aggregates and has collection semantics, so you call save(order) and findOverdueFor(customer) and get back Order objects with their lines. A DAO is a data-access concept: usually one per table, exposing table-level operations such as insertOrder(row), updateOrderStatus(id, status) or selectWhere with SQL-shaped parameters, and returning rows or partial objects. DAOs are fine inside infrastructure, and a repository implementation may use several of them internally. The problem is exposing DAO-style operations to the domain, which leaks the storage structure and enables partial updates that bypass the aggregate's rules and events.
How does Spring Data implement repository interfaces?
At startup Spring Data scans for interfaces extending Repository and creates a JDK dynamic proxy for each, backed by an implementation such as SimpleJpaRepository for the CRUD methods. Derived query methods like findByCustomerIdAndStatusIn are parsed into queries from the method name at startup, so a wrong property name fails the application start rather than a request. Methods annotated with @Query use the given JPQL or SQL, and @EntityGraph adds a fetch plan. Custom fragments, an interface plus an Impl class, are merged into the proxy for hand-written logic. At call time the proxy routes each method to the right part, inside the caller's transaction or a read-only transaction of its own.
Why avoid methods like updateStatus(id, status)?
Because it bypasses the aggregate. A method like updateStatus(id, SHIPPED) writes the column directly, so the rules the Order enforces are skipped: whether it is paid, whether a tracking number is required, which transitions are legal, and which domain events such as OrderShipped must be published. The same change can then be made correctly in one place and incorrectly in another, and the optimistic-locking version may not be incremented. The safe form is to load the aggregate, call a domain method such as order.ship(tracking) and save it, so the behaviour is always applied. Bulk updates for operational reasons are legitimate, but belong in explicit, audited infrastructure jobs.
How should list screens and reports be served?
Through a separate read path, not the aggregate repositories. Repositories are optimised for loading one aggregate to change it; a list screen needs a page of summaries, often joining data from several aggregates and projecting a few columns. Loading full aggregates for that causes N+1 queries, huge object graphs and finder methods multiplying on the repository. Instead I write query services that return read-only records, using JPQL constructor expressions, Spring Data interface or DTO projections, or plain JDBC with pagination. Full-text search goes to an index such as OpenSearch, and reports to SQL views or read models. This is CQRS-light: one database with separate read paths, and separate read stores only when needed.
What are the trade-offs of letting domain interfaces extend Spring Data types directly?
Letting the domain interface extend JpaRepository or ListCrudRepository saves an adapter class and some delegation code, and for simple CRUD applications that is often a reasonable choice. The costs are that the domain now depends on Spring Data, and the interface inherits generic methods such as deleteAll, saveAll and findAll that any caller can use, which weakens the aggregate's control and the domain language. JPA-specific behaviour such as flushing and lazy loading also leaks into the contract. A separate port with only the needed methods, implemented by an adapter that delegates to a Spring Data interface, keeps the domain framework-free and testable with in-memory fakes. Extending the narrow Repository marker is a middle ground.
How do repositories help future data architecture changes?
Because domain and application code talk to storage only through aggregate-shaped interfaces, the storage behind them can change without touching business logic. A caching layer can be added inside the repository implementation, reads can be routed to replicas, a bounded context can move from a relational database to a document store, as in the MongoOrderRepository example, or sharding can be introduced, all behind the same port. Shared contract tests run against the old and new implementations prove behavioural equivalence before switching. Keeping write repositories separate from read queries adds another option: reads can later move to dedicated read models or search indexes. Repositories preserve architectural options at low cost.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.