Skip to content
javahacks.dev
Architecture

Anemic Domain Model vs Rich Domain Model in Java Code

Compare an anemic domain model with a rich one in Java: where the rules live, an order example in both styles, tests, persistence and a practical way to move.

6 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the OpenJDK, Spring, Apache Maven and Gradle logos.

Martin Fowler called it an anti-pattern: objects with nothing but data, and a service layer doing all the thinking. A large share of Spring applications look exactly like that, and for some of them it is the right call. The useful question is what the shape costs you, and which part of a codebase would be cheaper to maintain if its objects defended their own rules.

The anemic version

java
@Entity
public class Order {
    @Id @GeneratedValue private Long id;
    private String status;
    private BigDecimal total;
    // getters and setters for everything
}

@Service
public class OrderService {
    public void pay(Order order, BigDecimal amount) {
        if (!"PLACED".equals(order.getStatus())) throw new IllegalStateException("cannot pay");
        if (amount.compareTo(order.getTotal()) != 0) throw new IllegalArgumentException("wrong amount");
        order.setStatus("PAID");
    }
}

The weakness is visible in the first class. Anyone can call order.setStatus("SHIPPED") on an unpaid order, from a controller, a batch job or a test fixture. The rule "an order is paid only when placed and the amount matches" lives in exactly one service method, and every new code path has to know to go through it. Nothing enforces that, so the third developer to touch the code eventually writes a second path that skips the check. A string stands for the state, so a typo such as "Paid" compiles.

The rich version

java
@Entity
public class Order {

    public enum Status { PLACED, PAID, SHIPPED }

    @Id @GeneratedValue private Long id;
    @Enumerated(EnumType.STRING) private Status status = Status.PLACED;
    @Embedded private Money total;

    protected Order() { }                         // for JPA

    public Order(Money total) {
        if (total.isNegative()) throw new IllegalArgumentException("total must not be negative");
        this.total = total;
    }

    public void pay(Money amount) {
        if (status != Status.PLACED) throw new IllegalStateException("cannot pay an order that is " + status);
        if (!amount.equals(total)) throw new IllegalArgumentException("amount must equal the total");
        status = Status.PAID;
    }

    public void ship() {
        if (status != Status.PAID) throw new IllegalStateException("only a paid order can ship");
        status = Status.SHIPPED;
    }

    public Status status() { return status; }
}

There is no setStatus. The only route to PAID is pay, and the only route to SHIPPED is ship, which requires PAID. An Order that exists is always in a state the rules allow, whoever holds a reference to it. Money is a value object with its own validation, and why that beats a bare BigDecimal is covered in modelling money and time. Hibernate 6.2 and later accept a record as an @Embeddable, so a small record Money(BigDecimal amount, String currency) works there.

The tests get cheaper

java
@Test
void cannotPayTwice() {
    Order order = new Order(Money.of("25.00"));
    order.pay(Money.of("25.00"));

    assertThrows(IllegalStateException.class, () -> order.pay(Money.of("25.00")));
}

@Test
void cannotShipBeforePayment() {
    Order order = new Order(Money.of("25.00"));

    assertThrows(IllegalStateException.class, order::ship);
}

No Spring context, no mocks, no database. The business rules end up in unit tests that run in milliseconds, which is the base of the pyramid in the testing strategy. In the anemic version the same two tests need the service, and usually a mocked repository too, because the rule sits next to the plumbing.

What the service still does

java
@Service
class PaymentService {

    private final OrderRepository orders;
    private final PaymentLedger payments;

    PaymentService(OrderRepository orders, PaymentLedger payments) {
        this.orders = orders;
        this.payments = payments;
    }

    @Transactional
    public void pay(long orderId, Money amount) {
        Order order = orders.findById(orderId).orElseThrow();
        order.pay(amount);
        payments.record(orderId, amount);
    }
}

The service loads the aggregate, tells it what to do, calls collaborators and sets the transaction boundary. It contains no rules about when an order can be paid. A useful test of where logic belongs is to ask whether it needs anything outside the object: if it needs only the object's own fields, it is a method on the object, and if it needs a repository or a payment gateway, it is a service.

Persistence is the real objection

JPA wants a no-argument constructor, which is why the rich class has a protected one. Use field access, with annotations on fields, so Hibernate fills in state directly and does not call behaviour methods. Three consequences are worth knowing before committing to the style.

An entity must be a non-final, mutable class, so a record cannot be an entity even though it can be an embeddable. Lazy collections exposed through behaviour methods can trigger queries from inside what looks like pure domain code, so keep collection access inside the aggregate and load what a use case needs in the repository. And Hibernate bypasses your constructor when it loads a row, so constructor validation protects creation but not data that was already invalid in the table. Mapping basics are in mapping your first entity.

A bug the rich version removes

Suppose finance asks for a rule: an order over 10,000 can only be paid after a manager approves it. In the anemic design the rule goes into OrderService.pay, and it works until a nightly import job that sets the status directly to PAID after reconciling bank files. Nobody changed that job, because nobody knew the rule existed, and the first large order it touches is marked paid without approval. In the rich design the rule goes into Order.pay, the import job has no way to reach PAID except through that method, and the same change that adds the rule fails to compile in the job. The compiler found the second caller for you. That is the practical gain, and it is larger than any argument about purity.

Where anemic is the better choice

  • CRUD screens over reference data, where the only rules are "required" and "unique" and a database constraint already enforces both.
  • Data transfer objects and read models, which should be plain by design.
  • Scripts and thin integration layers that move data between systems.
  • Domains with little behaviour, where behaviour methods would be ceremony around setters.

Calling a whole system either style is a mistake. A typical application has one or two aggregates with real rules, such as orders and subscriptions, and a long tail of lookup tables. Spend the design effort on the first group.

Moving from one to the other

  1. Pick one aggregate whose rules are scattered across several services.
  2. Move one rule into a method on the entity, then delete the setter it replaced. The compiler lists every caller you must change.
  3. Make the fields private and expose only the reads callers need.
  4. Replace strings and bare numbers that carry meaning with enums and value types.
  5. Repeat, using each production bug as the signal for the next rule to move.

Do it where the code is changing, not as a sweep. A rule nobody has touched in two years is not worth the diff. The wider vocabulary of aggregates and value objects is in DDD tactical patterns.

Mapping rich entities with JPA

Two JPA details deserve a note. Field access means Hibernate reads and writes the fields directly, so a behaviour method that adds to a collection must be allowed to run on a detached or lazy collection; load what a behaviour needs before calling it. And a method that changes state should be called inside a transaction, where Hibernate notices the change and writes it at commit, with no explicit save call. If an entity method is called outside a transaction, the change is lost silently, which is one more reason to keep the call in the application service.

Limits of the rich model

Domain objects do not replace validation at the API boundary, where the input is untrusted and the error needs to be a 400 with field names. They should not call repositories or the network, because that makes the unit tests above impossible. Logic that spans two aggregates, such as moving stock between warehouses, belongs in a domain service. Fowler's own description is short and worth reading, the Domain-Driven Design reference gives the vocabulary, and the single responsibility principle is the check that keeps a rich object from becoming a dumping ground.

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.