Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 119 ยท Architecture and Deployment

Layered Architecture: Controllers, Services and Repositories

Structure Java backends in layers - controllers, services and repositories, DTOs versus entities, mapping, transaction boundaries and a runnable layered mini app.

Small programs can live in one class. Real backends can't: a single endpoint touches HTTP parsing, validation, business rules, transactions, SQL and JSON. If all of that sits in one method, every change is risky, nothing can be tested in isolation, and two developers can't work on the same feature without colliding.

The most common answer in Java is a layered architecture: controllers handle the web, services hold the business logic, and repositories talk to the database. Spring's @RestController, @Service and @Repository stereotypes are named after exactly these layers. In this lesson you will learn what belongs in each layer, why data crossing the layers should use separate DTOs, where transactions start and end, and how to organize packages. Then you will build a complete layered mini app in plain Java: an HttpServer controller, a service with real business rules, and an H2 repository, all in one runnable program.

You should be comfortable with The DAO and Repository Patterns, Building a REST API with the JDK and Dependency Injection.

The three classic layers

TEXT
   HTTP request
        |
 +--------------+   parses requests, validates input shape, maps to/from DTOs,
 |  Controller  |   picks status codes. Knows HTTP. Knows nothing about SQL.
 +--------------+
        |  calls with plain values or command objects
 +--------------+   business rules, use cases, transaction boundaries,
 |   Service    |   coordination of repositories and other services.
 +--------------+   Knows neither HTTP nor SQL.
        |  calls with domain objects
 +--------------+   loads and saves domain objects. Knows SQL / JPA.
 |  Repository  |   Knows no business rules.
 +--------------+
        |
     Database

The single most important rule: dependencies point downward. A controller may call a service; a service may call repositories; never the other way around. A repository never calls a service, and a service never imports anything from the web layer (no HttpServletRequest, no ResponseEntity, no status codes). This keeps each layer replaceable: the same service can be called by a REST controller, a message listener, a scheduled job or a test.

What goes where

Concern Layer Example
URL, HTTP method, headers, status codes Controller POST /books/7/loans returns 201
JSON parsing, input shape ("is memberId a number?") Controller 400 for a malformed body
Business rules ("max 2 loans per member") Service throws BusinessRuleException
Transactions Service one use case = one transaction
Authorization of business actions ("only the owner may cancel") Service (or method security on it) @PreAuthorize on the service method
SQL, JPA queries, mapping rows to objects Repository SELECT ... WHERE borrowed_by = ?
Converting domain objects to response DTOs Controller (or a mapper it calls) BookView.from(book)

A domain layer is often added below or beside the service: the entities and value objects with the rules that belong to a single object (book.isAvailable(), money.add(other)). Rules that coordinate several objects or repositories live in services.

Business logic in services, not controllers

The fastest way to build an unmaintainable application is the fat controller: the handler method reads the request, runs SQL, applies rules and writes the response. It works, until you need the same rule in a batch job, or want to test the rule without starting a server.

The first example shows the core idea without any HTTP: a LoanService that depends on a BookRepository interface. The rule lives in one place and is tested with an in-memory fake repository, so no database is needed. That is the payoff of layering: the most important code (the rules) is the easiest to test.

Java A service with business rules and a fake repository

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that the service throws domain exceptions, not HTTP errors. It doesn't decide that "already borrowed" means 409 Conflict; the web layer does. A message listener could map the same exception to "send to the dead-letter queue" instead.

DTOs versus entities

An entity (or domain object) models what you store: a Member with an id, name, email, password hash, internal flags and relationships. A DTO (data transfer object) models what crosses a boundary: what a client sends in a request or receives in a response. They look similar at first, which tempts people to return entities directly. Don't. Separate types protect you in three ways:

  1. Security. Serializing an entity sends every field it has, including ones you add later. A passwordHash field added next year leaks the day it is added.
  2. Stability. Renaming a database column or splitting a table shouldn't break your public API. With DTOs, only the mapping changes.
  3. Fit. Requests and responses rarely match the entity. A "create member" request has a plain password and no id; a "member summary" response has a computed activeLoans count.

With JPA there is a fourth reason: serializing a managed entity can trigger lazy loading (or a LazyInitializationException) and even infinite recursion through bidirectional relationships, as discussed in Fetching Strategies and the N+1 Problem.

The example shows what Jackson does with an entity, and the DTO-based alternative:

Java Entities leak fields, DTOs don't

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The second half shows mass assignment: if you bind incoming JSON directly to an entity, the client can set fields it should never control, such as the id or an admin flag. Jackson fails on unknown properties by default, so binding to a narrow request DTO rejects the sneaky fields. (If your project turns FAIL_ON_UNKNOWN_PROPERTIES off, the extra fields are ignored instead, which is still safe because the DTO has nowhere to put them.)

Mapping between them

Mapping code is boring, which is a good thing. Options:

  • Static factory methods on the DTO, like MemberView.from(member). Simple, explicit, easy to find. This is the right default.
  • A mapper class per aggregate (MemberMapper) when mappings are many or need other beans.
  • MapStruct, an annotation processor that generates mapping code at compile time:
Java
@Mapper(componentModel = "spring")
interface MemberMapper {
    @Mapping(target = "activeLoans", expression = "java(member.loanIds().size())")
    MemberView toView(Member member);
}

MapStruct is type-safe and fast, because it generates plain Java. Avoid reflection-based mappers that copy fields by name at runtime; they hide mistakes until production.

Where transactions belong

A transaction should cover one use case: "borrow a book" must check availability, count loans and save the loan as one unit. That is exactly the scope of a service method, so the service layer owns transaction boundaries. In Spring you write @Transactional on service methods, as explained in Entity Lifecycle and Transactions.

Putting transactions in repositories is too fine-grained (each call commits separately, so a failure halfway leaves half the work done). Putting them in controllers is too coarse and drags HTTP concerns into transaction handling, such as holding a database transaction open while the response is serialized.

A complete layered mini app

Now all the pieces together, still without a framework:

  • Repository: JdbcBookRepository implements BookRepository with H2 and PreparedStatements.
  • Transactions: a tiny TransactionRunner sets autoCommit(false), commits on success and rolls back on any exception. It plays the role of @Transactional.
  • Service: LoanService with the rules from the first example, wrapped in a transaction.
  • Controller: BookController on HttpServer handles GET /books and POST /books/{id}/loans, maps request and response DTOs, and translates domain exceptions to status codes.
  • Composition root: main wires the objects together with constructors, exactly what a DI container does.

The server uses its default single-thread executor, so one JDBC connection is enough here; a real app would use a connection pool, as in Connection Pooling and DataSource.

Java Controller, service and H2 repository in one app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output from top to bottom and match each line to a layer. 404 for book 42 comes from the service's NotFoundException; 409 for the loan limit comes from a business rule; 400 for {} and {oops come from the controller before the service is ever called. The final GET /books shows that the two successful loans were committed. If you try changing the service to throw after setBorrower, the TransactionRunner rolls the update back.

The same app in Spring Boot

Each class above maps directly to a Spring stereotype. The plumbing disappears, the layers stay:

Java
@RestController
@RequestMapping("/books")
class BookController {
    private final LoanService loans;
    BookController(LoanService loans) { this.loans = loans; }

    @GetMapping
    List<BookView> list() {
        return loans.listBooks().stream().map(BookView::from).toList();
    }

    @PostMapping("/{id}/loans")
    @ResponseStatus(HttpStatus.CREATED)
    BookView borrow(@PathVariable long id, @Valid @RequestBody LoanRequest request) {
        return BookView.from(loans.borrow(id, request.memberId()));
    }
}

@Service
class LoanService {
    private final BookRepository books;
    LoanService(BookRepository books) { this.books = books; }

    @Transactional
    public Book borrow(long bookId, long memberId) { /* same rules as before */ }
}

interface BookRepository extends JpaRepository<Book, Long> {
    int countByBorrowedBy(long memberId);
}

@RestControllerAdvice
class ErrorHandling {
    @ExceptionHandler(BusinessRuleException.class)
    ProblemDetail conflict(BusinessRuleException e) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
    }
}

The @RestControllerAdvice replaces the catch blocks of the hand-written controller, @Valid replaces the manual memberId check (see Validation and Error Handling), @Transactional replaces TransactionRunner, and Spring Data generates the repository (Spring Data JPA).

Organizing packages: by layer or by feature

Package by layer groups classes by technical role:

TEXT
com.example.library.controller   BookController, MemberController, LoanController
com.example.library.service      BookService, MemberService, LoanService
com.example.library.repository   BookRepository, MemberRepository, LoanRepository
com.example.library.dto          BookView, MemberView, LoanRequest, ...

Package by feature groups everything one feature needs:

TEXT
com.example.library.books     BookController, BookService, BookRepository, Book, BookView
com.example.library.members   MemberController, MemberService, MemberRepository, Member, MemberView
com.example.library.loans     LoanController, LoanService, LoanRepository, Loan, LoanRequest

Package by layer is common in tutorials and small apps. Package by feature scales better: a change to loans touches one package, classes can be package-private (so LoanRepository can't be used from the members package by accident), and a feature can later be extracted into its own service, as discussed in Microservices. Inside a feature package you still have the three layers; only the folders change. Tools like ArchUnit (tests that assert "controllers must not access repositories") and Spring Modulith can enforce these boundaries automatically.

Beyond three layers: hexagonal architecture

Hexagonal architecture (ports and adapters) and clean architecture push the same idea further: the business core sits in the middle and defines ports (interfaces) for what it needs, like BookRepository or PaymentGateway. Adapters at the edges implement them: a JDBC adapter, a REST controller, a Kafka listener. The core depends on nothing technical; everything depends on the core.

You already did this in the first example: LoanService only knew the BookRepository interface, and both an in-memory fake and the JDBC implementation plugged in. For most CRUD-heavy services, classic layers with interfaces at the persistence boundary are enough. Reach for full hexagonal structure when the business logic is rich and long-lived, or when the same core must serve several kinds of adapters.

Common anti-patterns

  • Fat controllers with SQL and business rules inside handlers.
  • Anemic pass-through services whose methods only call repository.save(...) while the real rules are scattered in controllers. A thin service is fine for simple CRUD; logic belongs there once it exists.
  • Entities as API responses, which leak fields and couple the API to the schema.
  • Services that return ResponseEntity or take HttpServletRequest, which ties business logic to HTTP.
  • Repositories with business rules, such as a borrowIfAllowed() query that hides the rule in SQL.
  • Layer skipping: controllers calling repositories directly "just this once". It spreads quickly. If an endpoint really is pure data access, a thin service method costs a few lines.
  • An interface for every class "just in case". Interfaces pay off at real boundaries (persistence, external systems) and for test doubles. A FooService with exactly one FooServiceImpl and no fake is ceremony.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. The rule "a member may borrow at most two books" must apply to the REST API and to a nightly import job. Where should it live?

    Business rules belong in services. Controllers, jobs and listeners all call the same service method, so the rule exists once.
  2. 2. In the mini app, POST /books/3/loans with body {} returns 400 and the service is never called. Which layer produced the 400?

    Checking that memberId exists is input validation, done in the web layer. Business conflicts come from the service as 409.
  3. 3. Why should a service throw BusinessRuleException instead of returning an HTTP 409 status?

    Keeping HTTP out of the service lets message listeners, jobs and tests reuse it. The controller (or a controller advice) owns the mapping to 409.
  4. 4. A Member entity has a passwordHash field. A controller returns the entity directly as JSON. What happens?

    Jackson serializes all accessible properties. A response DTO controls exactly what leaves the server.
  5. 5. Where should a @Transactional boundary for "borrow a book" usually be placed?

    A use case should commit or roll back as one unit. Per-repository transactions commit halfway; controller-level transactions mix in HTTP concerns.

Summary

  • Classic layers: controller (HTTP, input shape, DTO mapping, status codes), service (business rules, use cases, transactions), repository (persistence). Dependencies point downward only.
  • Services throw domain exceptions; the web layer translates them to HTTP statuses, ideally in one central place.
  • Use request and response DTOs instead of entities at the API boundary: no leaked fields, no mass assignment, a stable API. Map with static factories, mapper classes or MapStruct.
  • The service method is the natural transaction boundary.
  • Interfaces at the persistence boundary make services testable with fakes; hexagonal architecture generalizes this into ports and adapters.
  • Prefer package by feature as apps grow, and enforce boundaries with package-private classes or tools like ArchUnit.

Next: Microservices takes these boundaries one step further and splits an application into independently deployed services.