Video in progress

The mapping layers between entity, domain model, DTO and event have multiplied. When is a separate model worth it, and how do you organize the mapping?

A separate model is worth it only for a boundary where things really change differently: an external API, an external event, a complex domain. Elsewhere I cut down the number of models. For mapping I use compile-time generation (MapStruct) or explicit hand-written code, not "magic" reflection-based mappers.

📖 Answer

The typical excess: UserEntity → UserDomain → UserDto → UserResponse → UserEvent, all with the same 12 fields. Adding a new field means changing 5 classes and 4 mappers, and if one is forgotten, the field silently disappears.

Which boundaries are real:

  • External API (DTO): almost always separate: a contract with clients, hiding sensitive fields;
  • Integration event: separate: it's versioned and other teams read it;
  • Domain vs JPA entity: only if the domain is complex or the persistence shape differs a lot. In a simple service, entity = domain model is fine;
  • DTOs between internal layers (service → controller): often unnecessary.

Mapping approaches:

@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR)
interface OrderMapper {
    OrderResponse toResponse(Order order);
}

unmappedTargetPolicy = ERROR is the most important setting: if a new field is added and not mapped, the build fails. MapStruct generates plain Java code, which you can read and debug.

I avoid reflection mappers like ModelMapper/Dozer: silent errors when names don't match, the IDE can't see them during refactoring, and they're slower.

For small records a static factory (OrderResponse.from(order)) is enough, with no need for generation either.

Before adding a new model, I ask myself: "when will these two shapes start to differ?" If the answer is "never", the model isn't needed.