Video in progress

In a big team, how do you establish a rule for how entities, DTOs and API models move between layers?

Entities never leave the persistence and domain layers: controllers and the external API work only with DTOs/records, and mapping happens inside the transaction, at the service boundary. I enforce the rule not with a document but with ArchUnit tests, a shared mapper approach and a code review checklist.

📖 Answer

Without a rule, we know what happens: entities go out of the controller straight as JSON, lazy associations get opened during serialization, the moment open-in-view is turned off you get LazyInitializationException everywhere, and every column change in the database breaks the API.

The boundaries I set:

  • controller → service: incoming command/request records;
  • service → controller: response DTOs, assembled inside the service method's @Transactional;
  • entities live only inside services and repositories;
  • events to other services also use a separate, versioned schema, not entities.

Where mapping happens: inside the transaction, at the end of the service method. Or even better, on read paths, with a DTO projection that never loads the entity at all. You can use MapStruct, but it can open lazy associations "without looking", so you need to review the generated code once.

Automatic enforcement:

@ArchTest
static final ArchRule noEntitiesInWeb = noClasses()
    .that().resideInAPackage("..web..")
    .should().dependOnClassesThat().areAnnotatedWith(Entity.class);

On top of that, spring.jpa.open-in-view=false effectively enforces this rule: code that tries to open an entity outside a transaction fails immediately.

Trade-off: DTOs are extra code and a source of mapping bugs. In small internal CRUD services I relax the rule (for example, just never serialize an entity to JSON). But for an external API, a module that many teams work on, or a long-lived service, that extra code pays for itself quickly: the API and the schema can evolve independently.