Skip to content
javahacks.dev
Architecture

Domain Driven Design Tactical Patterns in Java Explained

The building blocks of domain-driven design in Java: entities, value objects, aggregates, repositories, domain services and events, with short code for each.

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

Most Java business code ends up as a pile of getters and setters on entities, with the rules living in a OrderService that reaches into them. Nothing stops a caller from setting a negative quantity, shipping an order that was never paid, or adding a line to an order that has been closed. Domain-driven design's tactical patterns are a small set of building blocks that move those rules onto the objects that own the data, so illegal states cannot be built in the first place. This post goes through the seven blocks in the order you meet them in code: value objects, entities, aggregates, repositories, domain services, domain events and factories. Each gets a short Java 25 example from one shared order domain, and the last section maps them onto JPA without letting the database leak into the model.

Value objects

A value object has no identity. Two Money values of 10.00 USD are the same thing, interchangeable, and immutable once built. Java records are the natural fit, and the constructor is the place to refuse bad values:

src/main/java/dev/javahacks/order/domain/Money.javajava
package dev.javahacks.order.domain;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Currency;

public record Money(BigDecimal amount, Currency currency) {

    public Money {
        if (amount == null || currency == null) {
            throw new IllegalArgumentException("amount and currency are required");
        }
        amount = amount.setScale(currency.getDefaultFractionDigits(), RoundingMode.HALF_EVEN);
    }

    public static Money usd(String amount) {
        return new Money(new BigDecimal(amount), Currency.getInstance("USD"));
    }

    public Money plus(Money other) {
        requireSameCurrency(other);
        return new Money(amount.add(other.amount), currency);
    }

    public Money times(int quantity) {
        return new Money(amount.multiply(BigDecimal.valueOf(quantity)), currency);
    }

    private void requireSameCurrency(Money other) {
        if (!currency.equals(other.currency)) {
            throw new IllegalArgumentException("currency mismatch: " + currency + " vs " + other.currency);
        }
    }
}
java
Money total = Money.usd("19.99").times(3).plus(Money.usd("5.00"));
System.out.println(total);
Text
Money[amount=64.97, currency=USD]

The type does three jobs that a bare BigDecimal cannot. It carries the currency, so adding dollars to euros fails loudly. It fixes the scale, so 10, 10.0 and 10.00 are equal. And it holds the arithmetic, so no service re-implements rounding. Prefer value objects over primitives for anything with rules: Email, Quantity, Sku. The pattern is also the one with the least ceremony, which is why it is the best place to start.

Entities

An entity has an identity that outlives its attributes. An order is still order 1042 after its lines change. Equality is by id, and the object protects its own state transitions behind methods named in the language of the business, not setStatus:

src/main/java/dev/javahacks/order/domain/OrderStatus.javajava
package dev.javahacks.order.domain;

public enum OrderStatus { DRAFT, PLACED, PAID, SHIPPED, CANCELLED }

The rule "an order can only be shipped after payment" belongs on the order, as a method that throws when it is violated. You will see that method in the aggregate below. The failure to avoid is the anemic model, where entities are bags of fields and every rule sits in a service, because then each new caller must remember every rule. The entity equality pitfalls with generated ids are covered in JPA equals and hashCode.

Aggregates

An aggregate is a cluster of objects treated as one unit for changes, with one entity as its root. Outsiders hold a reference to the root only, and every change goes through it. That gives the root a place to enforce invariants that span the cluster, such as "the order total equals the sum of its lines".

src/main/java/dev/javahacks/order/domain/Order.javajava
package dev.javahacks.order.domain;

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.UUID;

public class Order {

    private final UUID id;
    private final List<OrderLine> lines = new ArrayList<>();
    private OrderStatus status = OrderStatus.DRAFT;
    private final List<DomainEvent> events = new ArrayList<>();

    public Order(UUID id) {
        this.id = id;
    }

    public void addLine(String sku, int quantity, Money unitPrice) {
        requireStatus(OrderStatus.DRAFT, "add a line");
        if (quantity <= 0) {
            throw new IllegalArgumentException("quantity must be positive");
        }
        lines.add(new OrderLine(sku, quantity, unitPrice));
    }

    public Money total() {
        return lines.stream()
                .map(l -> l.unitPrice().times(l.quantity()))
                .reduce(Money.usd("0"), Money::plus);
    }

    public void place() {
        requireStatus(OrderStatus.DRAFT, "place");
        if (lines.isEmpty()) {
            throw new IllegalStateException("an order needs at least one line");
        }
        status = OrderStatus.PLACED;
        events.add(new OrderPlaced(id, total()));
    }

    public void markPaid() {
        requireStatus(OrderStatus.PLACED, "pay");
        status = OrderStatus.PAID;
    }

    public void ship() {
        requireStatus(OrderStatus.PAID, "ship");
        status = OrderStatus.SHIPPED;
    }

    public List<OrderLine> lines() {
        return Collections.unmodifiableList(lines);
    }

    public List<DomainEvent> pullEvents() {
        var out = List.copyOf(events);
        events.clear();
        return out;
    }

    public UUID id() { return id; }
    public OrderStatus status() { return status; }

    private void requireStatus(OrderStatus expected, String action) {
        if (status != expected) {
            throw new IllegalStateException("cannot " + action + " an order that is " + status);
        }
    }
}

record OrderLine(String sku, int quantity, Money unitPrice) { }

An illegal sequence now fails where it is written:

java
Order order = new Order(UUID.randomUUID());
order.addLine("A-100", 2, Money.usd("19.99"));
order.ship();
Text
Exception in thread "main" java.lang.IllegalStateException: cannot ship an order that is DRAFT

Keep aggregates small. Load and save one per transaction, reference other aggregates by id and not by object, and the locking scope stays narrow. A giant Customer aggregate that owns every order it ever made turns each update into a contention point. The sizing arguments, with more examples, are in DDD aggregates, entities and value objects in Java.

Repositories

A repository makes an aggregate look like an in-memory collection: you get one by id and put it back. It is defined by the domain, in domain terms, and implemented by infrastructure:

src/main/java/dev/javahacks/order/domain/Orders.javajava
package dev.javahacks.order.domain;

import java.util.Optional;
import java.util.UUID;

public interface Orders {

    Optional<Order> find(UUID id);

    void save(Order order);
}

The interface lives next to the model and says nothing about SQL. The implementation, in an infrastructure package, may use JPA, JDBC or an in-memory map for tests. This is the dependency inversion discussed in dependency inversion beyond the slogan: the domain defines what it needs, and the database adapts to it. A repository returns whole aggregates. Reporting queries that cut across many orders do not belong here; give them their own read model.

Domain services

Some rules do not belong to any single entity: converting a total across currencies, checking a discount against a customer's history, deciding whether two orders can be merged. A domain service holds that logic as a stateless object named after the operation:

src/main/java/dev/javahacks/order/domain/DiscountPolicy.javajava
package dev.javahacks.order.domain;

import java.math.BigDecimal;

public class DiscountPolicy {

    private static final BigDecimal LOYALTY_RATE = new BigDecimal("0.05");

    public Money discountFor(Order order, int previousOrderCount) {
        if (previousOrderCount < 10) {
            return Money.usd("0");
        }
        BigDecimal off = order.total().amount().multiply(LOYALTY_RATE);
        return new Money(off, order.total().currency());
    }
}

The policy needs the order and a fact about the customer's history, and neither object should know about the other, which is the signal that the rule is a service. For an order totalling 64.97 USD and a customer with 12 previous orders it returns Money[amount=3.25, currency=USD], since 64.97 times 0.05 is 3.2485 and rounds half-even to 3.25. A domain service earns its place only when the logic truly spans objects. Do not name every OrderService method a domain service; application services that coordinate a use case (load, call the aggregate, save, publish) are a different layer, and they hold no business rules.

Domain events

An event is a fact that has happened, named in the past tense, that other parts of the system may care about. The place() method above records OrderPlaced without knowing who listens:

src/main/java/dev/javahacks/order/domain/OrderPlaced.javajava
package dev.javahacks.order.domain;

import java.util.UUID;

public record OrderPlaced(UUID orderId, Money total) implements DomainEvent { }
src/main/java/dev/javahacks/order/domain/DomainEvent.javajava
package dev.javahacks.order.domain;

public interface DomainEvent { }

The application service publishes whatever the aggregate collected, after the save succeeds. With Spring Data you can let the framework do it by marking a method with @DomainEvents on an aggregate, as described in the domain events section of the Spring Data reference. Events are what let a billing module react to a placed order without the order module importing billing. For how to carve those modules, see Spring Modulith.

Factories

When creating an aggregate is complicated, because it needs a generated id, defaults or a first line, put the creation in a factory so the constructor can stay strict:

java
public final class OrderFactory {

    public static Order startFor(String firstSku, int quantity, Money price) {
        Order order = new Order(UUID.randomUUID());
        order.addLine(firstSku, quantity, price);
        return order;
    }
}

Often a static method on the aggregate is enough. Reach for a separate factory class only when construction needs collaborators such as a clock or an id generator.

Applying them with JPA

The pragmatic route in a Spring app is to map the domain classes directly with annotations and accept the small compromise: a no-arg constructor and field access. Money becomes an @Embeddable, the aggregate root an @Entity, its lines an @ElementCollection or @OneToMany(cascade = ALL, orphanRemoval = true). Keep the setters out and let Hibernate use fields. The full set of mapping choices is in the Hibernate and JPA guide.

The stricter route keeps a persistence model separate and maps to and from the domain in the repository adapter. It costs a mapping layer and buys a domain that knows nothing about Hibernate. Start with the pragmatic route and split only when the two models drift.

Where this does not apply

For a CRUD screen over a table with no rules, these patterns are overhead, and a simple service over a Spring Data repository is the right size. They pay when the domain has real invariants, several people change the same rules, and the vocabulary matters. A layered design may be all you need for a long time, and its real costs are worth weighing first. When you do split a system along domain lines, service boundaries in DDD is the next step. The original source for the vocabulary is the DDD reference summary.

Also inHibernate
Taggedexplainer
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.