Sub topic 7
Mapping Entities to Response Records
This chapter covers how to turn a JPA entity into a response record. It assumes you can write a Spring Boot @RestController, that you know basic JPA (@Entity, relationships, lazy loading), and that you have seen record syntax. Earlier chapters explained why DTOs exist and how records are declared. Here the focus is the mapping step between the two.
Why the mapping step matters
An entity represents a database row and carries persistence concerns: a generated id, lazy relationships, version fields, and sometimes sensitive columns. A response record represents what a client is allowed to see. The mapping code is the only place where the two meet, so it is the place where you decide which fields leave the system.
Doing this explicitly gives you three things:
- Fields you do not copy cannot leak. A password hash on
Usernever reaches the client unless you write the line that copies it. - The JSON shape stays stable when the table changes. Renaming a column or adding a field to the entity does not change the API.
- Lazy relationships are touched at a moment you control, not by the JSON serializer at an arbitrary point.
The static factory method
The simplest mapping is a static method on the record itself. The record below is the response DTO used throughout this tutorial.
public record UserResponse(Long id, String name, String email) {
public static UserResponse from(User user) {
return new UserResponse(user.getId(), user.getName(), user.getEmail());
}
}The method reads three getters and calls the canonical constructor. It has no framework dependency, so you can call it from a service, a test, or a stream pipeline.
A service can then use it like this:
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
class UserQueryService {
private final UserRepository repository;
UserQueryService(UserRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
UserResponse get(Long id) {
User user = repository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("No user " + id));
return UserResponse.from(user);
}
@Transactional(readOnly = true)
List<UserResponse> all() {
return repository.findAll().stream().map(UserResponse::from).toList();
}
}UserResponse::from works as a method reference, which is why a static method with a single parameter is a convenient shape. Stream.toList() (Java 16 and later) returns an unmodifiable list, which fits a response that nobody should change.
Where to put the mapping code
There are three common places. None is wrong, but they have different costs.
| Location | Strength | Weakness |
|---|---|---|
| Static `from` method on the record | Easy to find, no extra class, works as a method reference | The DTO package depends on the entity class |
| Instance method on the entity, such as `user.toResponse()` | Short call sites | The entity now depends on the API layer |
| Separate mapper class or a library such as MapStruct | Keeps both classes free of mapping code, scales to many fields | More files, and generated code to understand |
For a small or medium application, the static factory is a good default. The dependency direction is acceptable because the API layer is allowed to know about the domain, and the domain does not know about the API. Avoid the second option for that reason: it reverses the direction.
Mapping inside the transaction
Mapping is the moment when lazy associations are read. Consider a User with a lazy collection of roles, and a response that lists role names.
import java.util.List;
public record UserDetailResponse(Long id, String name, List<String> roles) {
public static UserDetailResponse from(User user) {
List<String> roleNames = user.getRoles().stream()
.map(Role::getName)
.toList();
return new UserDetailResponse(user.getId(), user.getName(), roleNames);
}
}user.getRoles() triggers a query if the collection has not been loaded. That works only while the persistence context is open. If the mapping runs after the transaction has ended, Hibernate throws LazyInitializationException.
Two rules avoid this problem:
- Call
frominside the@Transactionalservice method, as in the example above, and return the record, not the entity. - Do not rely on Open Session in View. Spring Boot enables it by default through
spring.jpa.open-in-view=true, which keeps a session open during the web request and hides lazy-loading mistakes. Many teams set it tofalseso that errors show up in development instead of in production.
spring.jpa.open-in-view=falseBecause the service returns records, the controller has no reason to touch an entity. With the property turned off, any accidental lazy access from the web layer fails immediately.
The N+1 query problem
Mapping a list of entities that each touch a lazy collection issues one query for the list and one more per row. For 100 users that is 101 queries. The mapping code looks innocent, which is why this problem is easy to miss.
You have two ways to fix it:
- Fetch the association in the repository query, for example with
@EntityGraph. - Skip the entity and select only what you need, which the later chapter on Spring Data projections covers.
An entity graph looks like this:
import java.util.List;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
@EntityGraph(attributePaths = "roles")
List<User> findAllWithRolesBy();
}The By at the end of the method name is valid in a derived query and means "no condition". The graph tells JPA to load roles in the same query as the users. Mapping then reads data that is already in memory.
Null handling and defensive copies
A from method trusts its input. If you pass null, user.getId() throws NullPointerException. That is usually the right behavior, because a null entity means a bug in the caller. Do not hide it by returning null.
Nullable fields inside the entity need a decision. For a response record, you have three options:
- Copy the null and let Jackson write
nullor omit it, depending on your configuration. - Replace it with a default, such as an empty list for a missing collection.
- Reject it by using
Objects.requireNonNullin a compact constructor.
When the record holds a collection, copy it. The earlier chapters on compact constructors showed List.copyOf. In a mapping method, toList() on a stream already produces an unmodifiable list, so no extra copy is needed. If you pass the entity's own collection straight into the record, the record then holds a reference to a Hibernate-managed collection, which defeats the purpose of the DTO.
import java.util.List;
import java.util.Objects;
public record TeamResponse(Long id, String name, List<String> memberNames) {
public TeamResponse {
Objects.requireNonNull(name, "name");
memberNames = List.copyOf(memberNames);
}
public static TeamResponse from(Team team) {
return new TeamResponse(
team.getId(),
team.getName(),
team.getMembers().stream().map(User::getName).toList());
}
}Nested records
When an entity references another entity, the response usually nests a second record instead of exposing the child entity. Keep each nested record small and give it its own from method.
public record OrderResponse(Long id, CustomerSummary customer, long totalCents) {
public record CustomerSummary(Long id, String name) {
static CustomerSummary from(Customer customer) {
return new CustomerSummary(customer.getId(), customer.getName());
}
}
public static OrderResponse from(Order order) {
return new OrderResponse(
order.getId(),
CustomerSummary.from(order.getCustomer()),
order.getTotalCents());
}
}A nested record declared inside another record is implicitly static, so it needs no reference to an outer instance. Jackson handles it without extra configuration. Be aware of two cases:
- A bidirectional relationship (a
Customerwith a list ofOrder, and eachOrderwith aCustomer) is a cycle if you map both directions. Map only one direction in each DTO, and stop at a summary record. - If
order.getCustomer()is a lazy reference, callinggetName()loads it. This is the same transaction rule as before.
Mapping in the other direction
Request records are usually turned into entities, and the approach differs slightly. Do not add an toEntity method that exposes a setter-heavy entity to the DTO layer. Create or update the entity in the service, where you control the rules.
@Transactional
UserResponse create(CreateUserRequest request) {
User user = new User(request.name(), request.email());
User saved = repository.save(user);
return UserResponse.from(saved);
}For updates, load the entity and copy only the fields the client may change. Never copy the id from a request body onto an entity, because that lets a client overwrite a different row.
Common mistakes
- Returning the entity from a service "for now". The controller then serializes it and the lazy-loading and leakage problems return. Return a record from the service.
- Mapping outside the transaction. The symptom is
LazyInitializationException. Move thefromcall inside the transactional method. - Hiding the problem with Open Session in View. The application works, but each response may run extra queries that you did not plan for.
- Copying every field "just in case". A response record that mirrors the entity gives you the same coupling as exposing the entity. Include only what the client uses.
- Using a record as the entity. A JPA entity needs a no-argument constructor, mutable fields for Hibernate to populate, and the ability to be proxied. Records have none of these, so they cannot be entities. Use a normal class for the entity and a record for the DTO.
Summary of the approach
- Keep the entity inside the service layer.
- Write a static
frommethod on each response record. - Call it inside the transaction so lazy data can load.
- Fetch associations deliberately to avoid N+1 queries.
- Nest small records for related objects, and never create cycles.
Exercise
A controller method calls userService.find(id), which is annotated @Transactional and returns a User entity. The controller then calls UserDetailResponse.from(user), and with spring.jpa.open-in-view=false it throws LazyInitializationException on user.getRoles(). What are two changes that fix it, and which one is preferable?
Show answer
First, move the mapping into the service so that from runs inside the transaction, and have the service return UserDetailResponse. Second, fetch the roles in the repository query with @EntityGraph(attributePaths = "roles") so they are already loaded. The first change is preferable because it also keeps the entity out of the controller. The entity graph is a useful addition when the roles are always needed, and it also prevents N+1 queries when mapping lists.
Exercise
Write a response record ProductResponse with Long id, String name, and List<String> tags, plus a from(Product product) method. Product has getId(), getName(), and getTags() returning a Set<String>. Why should the record not store the Set directly?
Show answer
public record ProductResponse(Long id, String name, List<String> tags) { public static ProductResponse from(Product product) { return new ProductResponse(product.getId(), product.getName(), product.getTags().stream().sorted().toList()); } } The record should not store the entity's Set because that set may be a Hibernate-managed collection that is lazily loaded, mutable, and tied to the session. Copying into an unmodifiable list inside the transaction gives the record its own stable data, and sorting gives a predictable JSON order.