Skip to content
javahacks.dev
Architecture

Aggregates Entities and Value Objects in Java With Examples

Decide what is an entity, a value object and an aggregate in a Java domain model, size aggregates by consistency rules and avoid the common mapping traps.

8 min read
Summarize in AI
Flat illustration of an entity class mapped to a database table, with the Hibernate, MariaDB and Spring Boot logos.

Modeling decisions in a domain often reduce to three words. Is this an entity, a value object or part of an aggregate? Getting them right gives a model whose rules are enforced in one place and whose transactions are small. Getting them wrong gives bloated aggregates, lost updates and mapping pain. This post gives questions to ask and examples in Java. The other building blocks are in DDD tactical patterns.

Entity or value object

Ask: if two instances have the same attributes, are they the same thing?

ConceptSame attributes means same thing?Type
A customer named "Ana"No: two customers can share a nameEntity
10 USDYes: any 10 USD is as good as anotherValue object
An addressUsually yesValue object
An orderNo: identity mattersEntity
A date rangeYesValue object

Value objects are immutable and compared by content, which Java records do for free:

java
public record Address(String street, String city, String postalCode, String country) {}

An entity is compared by identity, with the id set once:

java
public class Customer {
    private final CustomerId id;
    private Address billingAddress;      // a value object replaced as a whole

    public void moveTo(Address newAddress) { this.billingAddress = newAddress; }
}

Changing an address creates a new Address and replaces it, rather than editing fields in place. The identity types (CustomerId) are value objects too, wrapping a UUID or long so the compiler distinguishes them from other ids.

Why not use primitives

void charge(long customerId, long orderId, long amount) has three longs that can be swapped silently. charge(CustomerId, OrderId, Money) cannot. Value objects also carry validation and behavior in one place (Money.plus).

What an aggregate is for

An aggregate is the unit inside which invariants must be true at the end of every transaction. Find them by asking which rules must hold immediately:

  • "An order's total equals the sum of its lines." Lines and order change together: one aggregate.
  • "A customer's credit limit must not be exceeded by their open orders." This spans the customer and many orders. Putting every order inside the customer aggregate would make it huge; treat it as an eventually consistent rule or enforce it with a reservation.
java
public class Order {                                   // root
    private final OrderId id;
    private final CustomerId customer;                 // reference by id
    private final List<OrderLine> lines = new ArrayList<>();

    public void addLine(Sku sku, int quantity, Money price) { /* enforce rules */ }
}

OrderLine is an entity or a value object inside the aggregate with no meaning outside it. Code outside the aggregate never holds an OrderLine reference; it calls the root.

Keep aggregates small

A large aggregate loads and locks a lot of data, and two users editing different parts conflict. Rules of thumb:

  1. Design around invariants, not around the object graph. A Customer does not contain its orders.
  2. Prefer many small aggregates linked by id.
  3. One transaction changes one aggregate. If a use case changes two, either they should be one aggregate or the second change is eventual and driven by an event.
  4. Use optimistic locking on the root (@Version) to detect concurrent edits, as described in locking failures.

Referencing across aggregates

java
public class Order {
    private final CustomerId customerId;       // good: an id
    // private Customer customer;              // bad: pulls another aggregate into this one
}

Holding the object invites changing it from inside Order, breaks transaction boundaries and drags lazy-loading problems with it (LazyInitializationException). Load the other aggregate through its repository when needed.

Mapping with JPA

Value objects map as @Embeddable:

java
@Embeddable
public record Address(String street, String city, String postalCode, String country) {}

Records as embeddables are supported by recent Hibernate versions (Hibernate 6.2 and later); check your version. The aggregate root is an @Entity, and its children use @OneToMany(cascade = ALL, orphanRemoval = true) so they live and die with the root. Child entities have no repository of their own. The traps: bidirectional associations that leak the root's internals, and exposing getLines() as a mutable list; return an unmodifiable view.

java
public List<OrderLine> lines() { return List.copyOf(lines); }

A sizing check

For each aggregate, list the rule it protects. If you cannot name an invariant that needs the pieces together, split it. If a rule spans two aggregates and must be immediate, merge them or reconsider the rule.

An aggregate with its rules written down

The order example becomes concrete when the invariants live in the root. Here is an Order that refuses to enter an invalid state, with a Money value object doing the arithmetic:

java
public record Money(BigDecimal amount, Currency currency) {

    public Money {
        Objects.requireNonNull(amount, "amount");
        Objects.requireNonNull(currency, "currency");
        amount = amount.setScale(currency.getDefaultFractionDigits(), RoundingMode.HALF_EVEN);
    }

    public static Money zero(Currency currency) {
        return new Money(BigDecimal.ZERO, currency);
    }

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

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

    private void requireSameCurrency(Money other) {
        if (!currency.equals(other.currency)) {
            throw new IllegalArgumentException("currency mismatch: " + currency + " vs " + other.currency);
        }
    }
}
java
public class Order {

    private final OrderId id;
    private final CustomerId customerId;
    private final List<OrderLine> lines = new ArrayList<>();
    private OrderStatus status = OrderStatus.OPEN;
    private long version;

    public Order(OrderId id, CustomerId customerId) {
        this.id = Objects.requireNonNull(id);
        this.customerId = Objects.requireNonNull(customerId);
    }

    public void addLine(Sku sku, int quantity, Money unitPrice) {
        requireOpen();
        if (quantity <= 0) {
            throw new IllegalArgumentException("quantity must be positive");
        }
        if (lines.size() >= 100) {
            throw new IllegalStateException("an order holds at most 100 lines");
        }
        lines.add(new OrderLine(sku, quantity, unitPrice));
    }

    public Money total() {
        return lines.stream()
            .map(OrderLine::subtotal)
            .reduce(Money.zero(currency()), Money::plus);
    }

    public void place() {
        requireOpen();
        if (lines.isEmpty()) {
            throw new IllegalStateException("cannot place an empty order");
        }
        status = OrderStatus.PLACED;
    }

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

    private void requireOpen() {
        if (status != OrderStatus.OPEN) {
            throw new IllegalStateException("order " + id + " is " + status);
        }
    }

    private Currency currency() {
        return lines.isEmpty() ? Currency.getInstance("USD") : lines.get(0).unitPrice().currency();
    }
}

Every rule from the earlier list sits in a method the outside world must go through. There is no setStatus, no public list to add to, and no way to hold an OrderLine and change it. The total is computed, not stored, so it cannot disagree with the lines.

Tests that read like the rules

Because the aggregate is plain Java, its rules need no database or Spring context to be checked:

java
class OrderTest {

    private final Order order = new Order(OrderId.next(), new CustomerId("c-1"));

    @Test
    void totalIsTheSumOfLines() {
        order.addLine(new Sku("A"), 2, usd("10.00"));
        order.addLine(new Sku("B"), 1, usd("5.50"));
        assertEquals(usd("25.50"), order.total());
    }

    @Test
    void emptyOrderCannotBePlaced() {
        assertThrows(IllegalStateException.class, order::place);
    }

    @Test
    void placedOrderRejectsNewLines() {
        order.addLine(new Sku("A"), 1, usd("10.00"));
        order.place();
        assertThrows(IllegalStateException.class,
            () -> order.addLine(new Sku("B"), 1, usd("1.00")));
    }
}

Hundreds of tests of this kind run in a fraction of a second, which is the practical payoff of keeping rules in the model and not in services.

Raising events from the root

The root is also the right place to record what happened, so other aggregates can react without being called inside the transaction. With Spring Data, extending AbstractAggregateRoot publishes registered events when the repository saves the aggregate:

java
public class Order extends AbstractAggregateRoot<Order> {

    public void place() {
        requireOpen();
        if (lines.isEmpty()) {
            throw new IllegalStateException("cannot place an empty order");
        }
        status = OrderStatus.PLACED;
        registerEvent(new OrderPlaced(id, customerId, total()));
    }
}
java
@Component
class CreditReservation {

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    void on(OrderPlaced event) {
        // update the customer's credit in a separate transaction, eventually consistent
    }
}

This is how the credit-limit rule from earlier is handled without putting every order inside the customer: the order commits, and the customer's side reacts. If the reaction fails, you need a compensating action, so decide up front what "credit exceeded after the fact" means to the business.

Concurrency on the root

Two people editing the same order is the case aggregates exist to protect. Optimistic locking on the root turns a lost update into an exception you can handle:

java
@Entity
public class OrderEntity {

    @Id private UUID id;
    @Version private long version;
    // fields mapped from the aggregate
}

When a second transaction saves a stale version, JPA throws an OptimisticLockException (Spring translates it to ObjectOptimisticLockingFailureException). Return 409 Conflict from the API and let the client reload and retry. That is cheaper and safer than pessimistic locks held across a user's think time.

Signs that the boundaries are wrong

The model usually tells you when an aggregate is drawn badly, if you look at how it behaves in production and not just on the whiteboard. An aggregate that is too large shows up as optimistic locking failures between users who edit unrelated parts, as slow loads that bring in children nobody asked for, and as a root with dozens of methods that serve different use cases. An aggregate that is too small shows up as a rule that must hold atomically and is split across two transactions, with a compensation job to repair the cases where they disagree.

When you see the first kind, look for the invariants the aggregate actually protects and move everything that is not part of one into its own aggregate, referenced by id. When you see the second kind, ask whether the rule really needs to hold immediately. Often the business accepts a short window, with a visible state such as "pending", and the split is correct after all. If the business does not, merge the two and accept the larger unit. Either way, the decision is cheap to revisit while the code is young and expensive after other teams depend on it, so write down the invariant next to the class. The next developer should be able to read why the boundary is where it is.

Where this does not apply

Reporting and read models do not need aggregates; query projections directly. Simple lookup data (country codes) is a table, not an aggregate. The boundaries between whole services follow the strategic design in service boundaries. Vaughn Vernon's *Implementing Domain-Driven Design* has the aggregate design rules, and the Hibernate documentation on embeddables covers the mapping. The Jakarta Persistence specification on embeddable classes defines the mapping rules for value objects.

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.