Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Why should a Spring REST API return DTOs instead of JPA entities, and what are the options for mapping between them: hand-written code, records with factory methods, MapStruct or ModelMapper?

A REST API should return DTOs because exposing JPA entities leaks internal fields, triggers lazy loading during serialisation with LazyInitializationException or N+1 queries, creates JSON cycles and ties the API to the database schema, while DTOs give a stable contract, per-use-case validation and control over what clients can write. For mapping, hand-written code or record factory methods are explicit and easy to debug for small models, MapStruct generates type-safe, fast mapping code at compile time and can fail the build on unmapped fields, and ModelMapper maps by reflection at runtime, which is convenient but can silently map wrong fields and is slower.

Why this question is asked

Returning an entity from a controller is the shortest path to a working endpoint, which is why it is everywhere in tutorials. It is also the source of some of the most common production problems in Spring applications, from hundreds of hidden queries to accidentally exposed fields. Interviewers ask this question to check that we understand those problems and that we can choose a mapping approach with reasons, not just habit. In this answer, we will see what goes wrong when entities leave the controller, what DTOs give us in return, and compare four ways of mapping between them, ending with where the mapping code should live.

1What Goes Wrong When Entities Are Returned

A JPA entity is a class mapped to a table and managed by Hibernate. When a controller returns it, Jackson, the JSON library, calls every getter to build the response. That causes four problems.

First, internal fields leak. Anything with a getter ends up in the JSON: audit columns, internal status flags, a passwordHash on a User. Second, lazy associations load during serialisation. A lazy collection is a placeholder that queries the database when first used; if the persistence context is closed, Jackson gets LazyInitializationException, and if it is still open, which Spring Boot's default Open Session in View allows, every order's customer and lines run their own query, the N+1 problem. Third, bidirectional relationships, where Order has lines and each OrderLine points back to its Order, make Jackson loop until it fails. Fourth, the API becomes the schema: renaming a column or splitting a table now breaks clients.

Java
@GetMapping("/users/{id}")
User get(@PathVariable long id) { return users.findById(id).orElseThrow(); }
// {"id":7, "email":"a@b.com", "passwordHash":"$2a$10$...", "failedLogins":3,
// "orders":[{"id":1, "user":{"id":7, "orders":[ ... ]}}]} -- leak, then an endless cycle

2What DTOs Give Us

A DTO, a data transfer object, is a simple class or record designed only for the API. Because it is separate from the entity, the API is a stable contract: the database can change and the DTO stays the same, with the mapping absorbing the difference.

DTOs also allow different shapes per use case. A CreateUserRequest has a password and validation annotations such as @NotBlank and @Email; a UserResponse never has the password; an admin view may have extra fields. And DTOs control what is written. If a request body is bound directly to an entity, a client can send fields such as role or balance and set them, which is called mass assignment. A request DTO only contains the fields a client is allowed to send, so there is nothing else to set.

Java
public record CreateUserRequest(@NotBlank @Email String email, @Size(min = 12) String password) { }
public record UserResponse(long id, String email) {
public static UserResponse from(User u) { return new UserResponse(u.getId(), u.getEmail()); }
}
@PostMapping("/users")
UserResponse create(@Valid @RequestBody CreateUserRequest req) {
return UserResponse.from(userService.register(req.email(), req.password())); // {"id":8,"email":"c@d.com"}
}

3Hand-Written Mapping and Record Factory Methods

The simplest mapping is code we write ourselves, often as a static factory method on the DTO record, as in UserResponse.from above. It is explicit: anyone can read exactly which field comes from where, the debugger steps straight through it, and the compiler catches type mismatches.

The cost is that it is repetitive for large models, and adding a field to the DTO does not remind us to map it unless we use a constructor, which records do: adding a component to the record breaks every call site until we pass the new value. For small and medium models, hand-written mapping is often the best choice.

4MapStruct: Generated at Compile Time

MapStruct is an annotation processor. We declare a mapper interface, and during compilation MapStruct generates an implementation with plain getter and setter or constructor calls, exactly as if we had written it by hand. Because the code is generated before runtime, it is type-safe and as fast as hand-written mapping, with no reflection.

Java
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR)
public interface UserMapper {
UserResponse toResponse(User user);
}
// Generated at build time, roughly:
// public UserResponse toResponse(User user) {
// if (user == null) return null;
// return new UserResponse(user.getId(), user.getEmail());
// }
// Add a field 'name' to UserResponse that User lacks -> compile error: Unmapped target property: "name"

With unmappedTargetPolicy set to ERROR, forgetting a field is a build failure rather than a silent null in production. The generated sources can be read and debugged. The costs are a build plugin to configure and some learning for nested and custom mappings.

5ModelMapper: Reflection at Runtime

ModelMapper and similar libraries inspect both classes with reflection at runtime and match properties by name, using heuristics for nested names. There is no interface to declare and nothing to generate; one call maps an object.

Java
ModelMapper mm = new ModelMapper();
OrderDto dto = mm.map(order, OrderDto.class);
// OrderDto.customerName <- order.getCustomer().getName() matched by name, as intended
// OrderDto.totalAmount <- order.getTotal()? or getTotalAmountBeforeTax()? depends on matching rules
Choosing a mapping approach
ApproachWhen it runsStrengthRisk
Hand-writtencompile time, our codeexplicit, easy to debugrepetitive for large models
Record factory methodcompile time, our codemapping next to the DTODTO depends on the entity
MapStructgenerated at compile timetype-safe, fast, unmapped-field errorsplugin setup, learning curve
ModelMapperreflection at runtimealmost no codesilent wrong matches, slower
For most Spring services, hand-written mapping for small models and MapStruct for larger ones.

Convenience is the benefit. The risks are that matching is decided at runtime by heuristics, so a renamed field can silently map to the wrong property or to nothing, errors appear only when that code runs, and reflection is slower than generated code. We can call validate() on its configuration in tests to catch unmapped properties, but the safety net is weaker than a compile error.

6Follow-up questions

Where should mapping live: controller, service or a mapper class?

Mapping between API DTOs and the domain belongs at the edge, so either in the controller or in a mapper class the controller uses, because the API shape is a web concern. The important constraint is timing: mapping that reads lazy associations must run while the data is loaded, so many teams let the service return a DTO or read model built inside the transaction, or fetch exactly what the DTO needs with a join fetch or projection. A dedicated mapper class, hand-written or MapStruct, keeps controllers thin and makes the mapping testable on its own.

Can a record factory method on the DTO depend on the entity?

It can, and it is convenient, but it means the API package depends on the persistence model. In a layered service that is usually acceptable. In a hexagonal service, where the web adapter should not know persistence entities, the factory would take a domain object instead.

Are DTOs still needed for internal admin endpoints?

Yes, for the same reasons: lazy loading, cycles and accidental exposure apply to every endpoint. Internal endpoints often become public later, and an entity-shaped contract is hard to take back.

7Conclusion

In this answer, we saw that returning JPA entities from a REST API leaks internal fields, triggers lazy loading with LazyInitializationException or N+1 queries, creates JSON cycles and couples clients to the schema, while DTOs give a stable contract, per-use-case validation and protection from mass assignment. For mapping, hand-written code and record factory methods are explicit and fine for small models, MapStruct generates fast, type-safe code at compile time and can fail the build on unmapped fields, and ModelMapper's runtime reflection is convenient but can silently map the wrong fields.

What to say in the interviewAbout 100 seconds aloud

Open with

I return DTOs instead of entities for a few reasons. If Jackson serialises an entity, it calls every getter, so internal fields like audit columns or a password hash leak, lazy associations either throw LazyInitializationException or, with Open Session in View, fire one query per item, which is N+1, and bidirectional relationships can loop forever.

Then, if they want more

It also makes the database schema the API contract, so a column rename breaks clients.

DTOs give a stable contract that the mapping protects, let me have different shapes and validation per use case, like a create request with @Email and a response without the password, and prevent mass assignment, because a request DTO only has the fields a client may set.

For mapping, for small models I write it by hand, often as a static from method on a record, because it is explicit and easy to debug, and records make missing fields a compile error at the constructor.

For larger models I use MapStruct, which generates plain mapping code at compile time, so it is type-safe and as fast as hand-written code, and with unmappedTargetPolicy ERROR a forgotten field fails the build. I avoid ModelMapper in most cases, because it matches by name with reflection at runtime, which can silently map the wrong field and is slower.

The mapping itself I put in a mapper class at the web edge, making sure it runs while the data it needs is loaded.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why should a Spring REST API return DTOs instead of JPA entities, and what are the...": https://scrivio-interview-library.netlify.app/java/application-architecture/4b99686971/