Video in progress

What is an anemic domain model, and why is it sometimes called an anti-pattern?

In an anemic model, entities are just data boxes with getters/setters, and all the business rules live in services. The problem is that the rules get scattered and an object can easily end up in an invalid state. But in plain CRUD systems it's often a perfectly fine choice.

📖 Answer

A typical Spring project:

order.setStatus(Status.PAID);
order.setPaidAt(Instant.now());
order.setTotal(order.getTotal().subtract(bonus));

These three lines are in OrderService, two of them are in AdminService, and the same thing, slightly different, is in WebhookHandler too. In one of them, setting paidAt was forgotten. The entity accepts any combination.

A richer model:

public void markPaid(Clock clock) {
    if (status != Status.NEW) throw new IllegalStateException("Faqat yangi buyurtma to'lanadi");
    this.status = Status.PAID;
    this.paidAt = Instant.now(clock);
}

The rule is in one place, it can't be bypassed (there's no setter), and it can be checked with a plain unit test without Spring.

Why "sometimes": if the application mostly fetches and stores data and has almost no rules, a rich model only adds complexity. An anemic model isn't a mistake in itself: the problem appears when the rules multiply and start getting duplicated in services. If you notice that, it's time to move the rule into the entity or a small domain object (Money, Period).

One note: when adding behavior to a JPA entity, don't inject service beans into it. The entity should work only with its own data.