Skip to content
javahacks.dev
Architecture

Repository Pattern Spring Data Overlap Explained Clearly

Compare the repository pattern with Spring Data repositories: what each is for, when a domain interface over Spring Data helps and when it adds nothing.

6 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the Spring, Hibernate, Spring Boot, Swagger and Apache Maven logos.

The repository pattern came from domain-driven design: the domain asks for aggregates through something that looks like an in-memory collection, and the storage details stay behind it. Spring Data's Repository interfaces look the same. The question is whether you need both.

What Spring Data gives you

java
public interface OrderRepository extends JpaRepository<Order, Long> {
    List<Order> findByCustomerAndStatus(String customer, Status status);

    @Query("select o from Order o join fetch o.lines where o.id = :id")
    Optional<Order> findWithLines(@Param("id") Long id);
}

The interface is implemented at startup, and services inject it. For many applications this is enough: the service layer depends on a Spring Data interface, the entity is the domain object, and transactions sit in the service. It is fast to build and easy to read.

What the pattern asks for

In the classic form, the repository interface belongs to the domain and speaks its language:

java
// domain package, no Spring or JPA imports
public interface Orders {
    Optional<Order> byId(OrderId id);
    List<Order> awaitingPayment(CustomerId customer);
    void save(Order order);
}

An adapter in the infrastructure package implements it with Spring Data:

java
@Repository
class JpaOrders implements Orders {
    private final OrderJpaRepository jpa;
    private final OrderMapper mapper;

    JpaOrders(OrderJpaRepository jpa, OrderMapper mapper) { this.jpa = jpa; this.mapper = mapper; }

    public Optional<Order> byId(OrderId id) { return jpa.findById(id.value()).map(mapper::toDomain); }
    public List<Order> awaitingPayment(CustomerId c) {
        return jpa.findByCustomerAndStatus(c.value(), "AWAITING_PAYMENT").stream().map(mapper::toDomain).toList();
    }
    public void save(Order order) { jpa.save(mapper.toEntity(order)); }
}

The domain Order is a plain class with behaviour. OrderEntity is the JPA mapping. The mapper converts between them. This is the shape used in hexagonal architecture.

What the extra layer costs

  • A mapper and a second class for every aggregate.
  • Lost conveniences: lazy loading, dirty checking and save semantics now depend on your mapping code.
  • More places to change for each new field.

What it buys

  • The domain compiles and tests without Spring or JPA on the classpath, so domain tests run in milliseconds.
  • Entity design can follow database needs while the domain model follows business needs.
  • Query names speak the business language (awaitingPayment), not method-name syntax.
  • Storage can change (a second store, an event log) without touching the domain.

A middle path

Often the best answer is smaller than either extreme. Use the entity as the domain object, and still hide Spring Data behind an interface that you own for the aggregates with real rules:

java
public interface Orders {
    Optional<Order> byId(Long id);
    void save(Order order);
}

Spring Data can implement it directly if the interface extends Repository<Order, Long> and declares only the methods you want, so there is no adapter. You limit the surface (no deleteAll, no findAll on a big table) without a mapping layer. Keep entities with business methods, as in rich domain models.

One repository per aggregate

A repository loads and saves aggregate roots, not every table. A repository for OrderLine lets code change a line without going through Order and its rules. The reasoning is in DDD aggregates. Reporting queries that cross aggregates belong to separate read-only query classes.

Do not leak entities

Returning JPA entities from a service to the web layer ties your API to your schema and invites lazy-loading failures, see LazyInitializationException. This is independent of the repository question: map to view records at the boundary.

Choosing

SituationChoice
CRUD service, little logicSpring Data directly
Rich domain, long-lived systemDomain interface, adapter, separate entity if needed
Domain rules, one persistence technologyNarrow Repository interface, entity as domain object
Need to swap storesDomain interface and adapters

A port in the domain and an adapter on Spring Data

When the extra layer is worth having, it is a small interface owned by the domain and one class that implements it with Spring Data. The domain code sees only the interface:

java
// domain package, no Spring imports
public interface Orders {
    Optional<Order> byId(OrderId id);
    void add(Order order);
    List<Order> openFor(CustomerId customer);
}

// infrastructure package
@Repository
class JpaOrders implements Orders {

    private final OrderJpaRepository jpa;
    private final OrderMapper mapper;

    JpaOrders(OrderJpaRepository jpa, OrderMapper mapper) {
        this.jpa = jpa;
        this.mapper = mapper;
    }

    @Override
    public Optional<Order> byId(OrderId id) {
        return jpa.findById(id.value()).map(mapper::toDomain);
    }

    @Override
    public void add(Order order) {
        jpa.save(mapper.toEntity(order));
    }

    @Override
    public List<Order> openFor(CustomerId customer) {
        return jpa.findByCustomerIdAndStatus(customer.value(), "OPEN").stream().map(mapper::toDomain).toList();
    }
}

The mapper is the cost: every aggregate needs a domain class, an entity class and the conversion between them, and a change to a field is made in three places. The benefit shows when the domain model differs from the table shape, and when tests of business rules run with an in-memory implementation of Orders.

The test that the port makes possible

With the port, a rule can run in a test with no Spring and no database:

java
class InMemoryOrders implements Orders {
    private final Map<OrderId, Order> store = new HashMap<>();

    public Optional<Order> byId(OrderId id) { return Optional.ofNullable(store.get(id)); }
    public void add(Order order) { store.put(order.id(), order); }
    public List<Order> openFor(CustomerId c) {
        return store.values().stream().filter(o -> o.customer().equals(c) && o.isOpen()).toList();
    }
}

@Test
void cannotCancelShippedOrder() {
    var orders = new InMemoryOrders();
    var order = Order.shipped(new OrderId(1));
    orders.add(order);
    assertThrows(IllegalStateException.class, () -> new CancelOrder(orders).execute(new OrderId(1)));
}

The test runs in milliseconds and says nothing about SQL. A second test against the real adapter and a database covers the mapping. Together they split the risk into two small, fast checks.

When the extra layer is waste

If the entity is the domain object, and the service methods are thin, the port repeats the Spring Data interface with different names. A CRUD application with a few rules gains nothing from it, and every new field costs a mapper edit. The signal is a mapper that copies fields one to one and a port whose methods match the repository methods. In that situation, use Spring Data directly and enforce the boundary by convention: services use repositories, controllers use services.

SituationChoice
Rich domain, rules beyond validationPort and adapter
CRUD with an admin screenSpring Data directly
Several storage backends for one modelPort and adapters
Team new to the frameworkSpring Data directly, add the port when pain appears
Heavy reporting queriesDirect repository or SQL, outside the aggregate

Do not hide the useful parts

A repository interface that offers only findById and save forces every other need into the service as stream filters over a loaded list. Put queries that the database can answer in the repository, with a name that states the business meaning, openFor(customer), and not a generic findAll followed by filtering in memory. A port is meant to express what the domain asks, and that includes the questions that are cheap for the storage to answer and expensive for the application.

Decide per aggregate, not per project

The choice does not have to be the same for the whole application. An order with pricing rules, state transitions and invariants earns a port and an adapter. A table of country codes, a list of feature flags or a log of audit entries is plain data, and a Spring Data repository used directly is the honest design. Mixed codebases are normal, and the rule that keeps them readable is a naming convention: types ending in Repository are Spring Data interfaces used by services, and domain ports carry business names such as Orders and Customers.

Review the decision when the aggregate changes. A simple entity that grows rules over a year may deserve promotion, and the move is easier than it sounds: introduce the port, make the existing repository its first implementation, and let the mapper start as a straight copy.

Where this does not apply

Standards-based alternatives exist: Jakarta Data defines repository interfaces as a specification. For the broader layering see layered architecture. The reference is Spring Data repositories, and Fowler's definition is the origin.

Also inHibernate
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.