Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 57 ยท Architectural and Modern Patterns

Repository and Unit of Work

Separate persistence from domain logic with the Repository pattern, test with in-memory repositories, and group changes into one transaction with Unit of Work.

Most applications store data, and the easiest way to write that code is to sprinkle SQL (or ORM calls) everywhere: in controllers, in services, in helper functions. It works until you want to test a rule without a database, change the storage, or make sure that three related changes either all happen or none do.

Two patterns address this. A Repository hides storage behind an interface that looks like a collection of domain objects. A Unit of Work tracks all the changes made during one business operation and saves them together, as a single transaction.

Repository

Collection feel add, get, find, remove: like a list of orders.
Hides storage SQL, files or memory: the domain does not care.
Test friendly Swap in an in-memory version for fast tests.
1 / 2

The problem: persistence everywhere

Here is the kind of code that makes testing painful. The business rule (a customer cannot place an order that exceeds their credit limit) is tangled with database calls:

Java
class OrderService {
    void place(long customerId, long amountCents) throws SQLException {
        try (Connection c = DriverManager.getConnection(URL)) {
            var rs = c.createStatement()
                      .executeQuery("SELECT credit FROM customers WHERE id=" + customerId);
            rs.next();
            if (rs.getLong(1) < amountCents) throw new IllegalStateException("over limit");
            c.createStatement().executeUpdate("UPDATE customers SET credit = credit - " + amountCents);
            c.createStatement().executeUpdate("INSERT INTO orders ...");
        }
    }
}

This snippet is read-only; it also has an SQL-injection hazard and no transaction. To test the credit rule you need a running database. The rule and the plumbing cannot be separated.

Repository: a collection-like interface

A repository gives the domain layer an interface shaped by what the domain needs, for example customers.get(id), orders.add(order), orders.findByCustomer(id). The domain code does not know whether those calls hit MySQL, a REST service or an array.

Some rules of thumb:

  • Name methods in business terms (findOverdueInvoices), not storage terms (selectWhereDueDateLessThan).
  • One repository per aggregate root: an object such as Order that owns its line items. You load and save the whole aggregate, not each line separately.
  • Return domain objects, not raw rows.
Node.js An in-memory repository makes rules testable

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 node:readline or process.stdin), it gets the next line from this box.

OrderService is tested in milliseconds, without a database. A production version would add SqlCustomers and SqlOrders classes that implement the same methods; OrderService would not change. The in-memory repositories here are a stand-in for real database code, and a real implementation still needs its own tests against a real database to prove the SQL is right.

Repository versus DAO versus ORM

You will see the terms mixed up:

  • A DAO (data access object) is a thin wrapper around one table's queries. It is storage-shaped.
  • A repository is domain-shaped: it speaks about aggregates and business queries.
  • An ORM (Hibernate, Eloquent, SQLAlchemy) is a tool that maps objects to tables. A repository is often built on top of an ORM; the ORM is the implementation detail.

Some people say an ORM already is a repository and a unit of work (Hibernate's Session is both). That is partly true, and a wrapper is not always worth it. Add your own repository when you want the domain to stay independent of the ORM, when queries deserve business names, or when you need an easy fake for tests.

Unit of Work: save everything together or nothing

Placing an order changes several objects: the customer's credit goes down, a new order appears, stock is reduced. If the third step fails after the first two were saved, the data is inconsistent. A Unit of Work collects the changes during one business operation and applies them in a single transaction on commit(). If something fails, rollback leaves storage as it was.

sequenceDiagram
    participant S as Service
    participant U as UnitOfWork
    participant D as Database
    S->>U: registerNew(order)
    S->>U: registerDirty(customer)
    S->>U: commit()
    U->>D: BEGIN
    U->>D: INSERT order, UPDATE customer
    U->>D: COMMIT

The service only registers changes. The unit of work decides when and how they reach the database.

Node.js A unit of work with commit and rollback

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 node:readline or process.stdin), it gets the next line from this box.

In the failed call, the customer update was applied first and the order insert then threw. The rollback put the customer back, so credit and order count are unchanged. A real unit of work uses the database's own BEGIN/COMMIT/ROLLBACK; the snapshot copy here is only a stand-in that makes the all-or-nothing behavior visible.

What real unit-of-work implementations add

  • Change tracking. ORMs detect which loaded objects were modified (dirty checking) so you do not call registerDirty yourself.
  • Identity map. Loading the same row twice within one unit returns the same object, avoiding two conflicting copies.
  • Ordering. Inserts and deletes are ordered so foreign keys stay valid.
  • Scope. One unit per request or per use case, never shared across threads or requests.

Frameworks give you this under other names: DbContext.SaveChanges() in Entity Framework, a Hibernate/JPA EntityManager and @Transactional, SQLAlchemy's Session, Django's transaction.atomic().

When not to use them

A tiny CRUD app or script rarely needs either pattern; calling the ORM directly is simpler, and an extra layer is just more code. Reach for a repository when business rules are non-trivial, when you need to test them in isolation, or when the storage might change. Reach for a unit of work when one operation touches several objects that must stay consistent. Avoid leaky repositories that expose query builders or ORM types in their signatures, because the domain is then coupled to the ORM again.

These patterns work hand in hand with Dependency Injection in Practice (so a service receives its repositories) and with the Dependency Inversion Principle (the domain owns the repository interface).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main goal of the Repository pattern?

    A repository presents aggregates as if they were an in-memory collection, so domain code does not depend on SQL, an ORM or a file format.
  2. 2. Why is an in-memory repository useful in tests?

    The service runs against a fast fake, but real SQL implementations still need their own tests against a real database.
  3. 3. What does a Unit of Work do on commit()?

    Changes are collected during the operation and written together, so either all of them are saved or none.
  4. 4. In the Unit of Work example, why were the credit and order count unchanged after the failed order?

    The simulated failure threw an error after one change was applied, and the catch block restored the snapshot taken before the commit.
  5. 5. Which is a sign of a leaky repository?

    Exposing ORM types makes callers depend on the ORM again, which defeats the point of hiding persistence.

Summary

  • A Repository exposes aggregates through domain-shaped methods and hides the storage technology.
  • In-memory repositories make business rules fast to test; real implementations still need integration tests.
  • A Unit of Work records new, changed and removed objects and commits them as one transaction, or rolls back.
  • ORMs often already provide both; wrap them when you want domain independence or business-named queries.
  • Keep one unit of work per use case or request, and one repository per aggregate root.
  • Skip both in tiny CRUD apps where they only add layers.

Next lesson: MVC, MVP and MVVM.