Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Should repositories be exposed directly to controllers or other modules? Describe the layering rules you would set for Spring Data repositories in a modular monolith.

Repositories should not be exposed to controllers or to other modules. Each module keeps its repositories inside its own persistence layer, with one repository per aggregate root, and offers a service API that defines transactions and fetch plans; controllers and other modules call that service. The rules are enforced with Spring Modulith or ArchUnit tests, and Spring Data REST, which turns repositories into HTTP endpoints, is used only where that direct coupling is a deliberate choice.

Why this question is asked

In a small service, injecting a repository straight into a controller feels efficient. In a modular monolith with twenty teams and forty modules, the same habit turns into a web of hidden dependencies: one team renames a column and three other modules break, and nobody can tell which code owns which table. Interviewers ask this at a senior level to see whether we can turn a vague sense of good layering into rules that a team can follow and a build can check. In this answer, we will recap what a modular monolith is, see what goes wrong when repositories leak, set the layering rules one by one with their reasons, show how to enforce them in tests, and place Spring Data REST in that picture.

1A Quick Recap: Modules, Aggregates and Repositories

A modular monolith is one deployable application split into modules with clear boundaries, such as orders, billing and catalogue. Each module owns its data and exposes a small public API. The idea is to get most of the independence of microservices without the network calls and deployment overhead.

An aggregate, a term from domain-driven design, is a group of objects that change together and are saved as one unit, such as an Order with its OrderLines. The aggregate root is the entry point, here Order: other code changes lines only by asking the order. A Spring Data repository is the object that loads and saves entities, and Spring Data generates its implementation from an interface.

2What Goes Wrong When Repositories Leak

Suppose the billing module needs the total of an order and injects OrderRepository from the orders module. It works on the first day. But now billing depends on the Order entity's fields, on its lazy associations and on the transaction boundaries the caller happens to have. When the orders team adds a field or changes a mapping, billing's code changes behaviour without anyone in billing touching it.

The same happens with controllers. A controller that calls orderRepository.findById and returns the entity to JSON triggers lazy loading outside a transaction, runs one query per association, and makes the database schema part of the public HTTP contract. Every rule below exists to stop one of these leaks.

3The Layering Rules

Rule one: repositories are internal to their module. In Java terms, the repository interfaces live in an internal package of the module, and only that module's services use them. Other modules never inject them.

Rule two: one repository per aggregate root, not per table. There is an OrderRepository but no OrderLineRepository, because lines are saved through their order. This keeps the aggregate's rules, such as the order total matching its lines, in one place that cannot be bypassed.

Rule three: controllers call services, not repositories. The service method is where the transaction starts, with @Transactional, and where the fetch plan is decided: which associations to load, through an entity graph or a fetch join, so the controller receives a complete result. The service also maps entities to response objects, so the entity never leaves the module.

Rule four: modules talk to each other through their public service API or through events, never through each other's entities. Billing asks orders for an OrderSummary record through OrdersApi.summary(orderId), and the orders module decides how to build it.

Step throughAllowed dependencies inside one module
  1. Controller (web)Calls services only; maps HTTP to requests
  2. Module service APIPublic; transactions, fetch plans, DTOs
  3. Domain modelAggregates and their rules
  4. Repositories (internal)One per aggregate root; never visible outside
  5. Database tablesOwned by this module only

5 layers, from the top down. Step through them one at a time.

Each layer may use the one below it; other modules see only the service API.

4The Rules in Code

Here is the shape of an orders module that follows the rules. The internal package holds the repository; the public API returns a record instead of an entity.

Java
// orders/OrdersApi.java (public)
public interface OrdersApi {
OrderSummary summary(long orderId);
}
public record OrderSummary(long id, BigDecimal total, String status) { }
// orders/internal/OrderRepository.java (package-private module internals)
interface OrderRepository extends JpaRepository<Order, Long> {
@EntityGraph(attributePaths = "lines")
Optional<Order> findWithLinesById(long id);
}
// orders/internal/OrderService.java
@Service
class OrderService implements OrdersApi {
private final OrderRepository repo;
OrderService(OrderRepository repo) { this.repo = repo; }
@Transactional(readOnly = true)
public OrderSummary summary(long id) {
Order o = repo.findWithLinesById(id).orElseThrow();
return new OrderSummary(o.getId(), o.total(), o.getStatus().name());
}
}
// billing calls ordersApi.summary(42) -> OrderSummary[id=42, total=99.50, status=PAID]

Notice that billing cannot even see OrderRepository: it is not public, and it lives in an internal package. The fetch plan, loading lines with an entity graph, is a decision of the orders module, made once in the service.

5Enforcing the Rules in the Build

Rules in a wiki drift. Rules in tests do not. Spring Modulith treats each direct sub-package of the application's main package as a module and, by default, treats sub-packages of a module as internal. Its verification test fails the build when one module uses another module's internal types or when modules depend on each other in a cycle.

Java
class ModularityTests {
@Test
void verifyModules() {
ApplicationModules.of(Application.class).verify();
}
}
// Fails with a violation such as:
// Module 'billing' depends on non-exposed type ...orders.internal.OrderRepository

ArchUnit does the same job without adopting Spring Modulith, with rules we write ourselves, for example that classes annotated @RestController must not depend on classes assignable to Repository, and that classes in ..internal.. packages are accessed only from their own module. Either way, the rule now fails a pull request instead of waiting for someone to notice it in review.

6Where Spring Data REST Fits

Spring Data REST does the opposite of everything above on purpose: it scans repositories and publishes them as HTTP resources with paging, sorting and links. A repository with no controller suddenly has GET, POST, PUT and DELETE endpoints.

That is useful for internal admin tools, prototypes or simple reference data, where the table really is the API and nobody minds the coupling. It is risky in a module that has business rules, because it lets callers bypass the service layer. In a modular monolith I would allow it only in a module designed for it, set spring.data.rest.detection-strategy to annotated so that only repositories marked with @RepositoryRestResource are exported, and review each one.

7Follow-up questions

Is it ever fine for a controller to call a repository directly?

In a tiny service with no business rules, a read-only endpoint that returns a projection can be fine. But once there are transactions, fetch plans or rules, the service layer pays for itself, and consistency matters more than the few lines saved. In a modular monolith I would not make exceptions.

How should one module read another module's data for reports?

Through the other module's API, or, for heavy reporting, through a read model the owning module publishes, such as a database view or events that the reporting module stores in its own tables. Reading another module's tables directly brings back the coupling the boundaries were meant to remove.

Why one repository per aggregate and not per table?

Because the aggregate is the unit of consistency. If OrderLine had its own repository, code could add a line without going through Order, and the order total or status rules would be skipped. Saving the root saves its parts through cascades, and the rules stay in one place.

8Conclusion

In this answer, we saw that exposing repositories to controllers or other modules spreads entity details, lazy loading and transaction assumptions across the code. The rules are simple: repositories are internal to their module, there is one per aggregate root, controllers call services that own transactions and fetch plans, and modules talk through public APIs. Spring Modulith or ArchUnit tests keep those rules true, and Spring Data REST is a deliberate exception rather than a default.

What to say in the interviewAbout 100 seconds aloud

Open with

No, I would not expose repositories to controllers or to other modules. In a modular monolith each module owns its tables, and its repositories are internal details. I put them in an internal package, so other modules cannot even see them.

Then, if they want more

I also keep one repository per aggregate root rather than per table, so for orders there is an OrderRepository but no repository for order lines, because lines must change through the order to keep its rules intact.

Controllers call the module's service, and the service is where the transaction starts and where I decide the fetch plan, for example an entity graph that loads the lines, so the controller gets a complete result and never triggers lazy loading.

The service returns DTOs or records, not entities, so the entity model is not part of the HTTP contract or of other modules' code. Between modules, the rule is the same: they call each other's public service API, or react to events, never each other's repositories. To make this stick, I would enforce it in the build.

Spring Modulith's verify test treats sub-packages as internal and fails when a module uses another module's internals; ArchUnit can express the same rules if we are not using Modulith.

Finally, Spring Data REST publishes repositories straight as HTTP endpoints, which is the opposite of these rules, so I would only use it where that coupling is intended, like an admin or reference-data module, with the annotated detection strategy.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Should repositories be exposed directly to controllers or other modules? Describe the...": https://scrivio-interview-library.netlify.app/databases/spring-data-jpa/ef4fc81504/