Sub topic 7
Mapping entities to response records
This chapter assumes you know basic Java and JPA, can write a Spring Boot @RestController, and have seen records and Bean Validation in earlier chapters. Here you will turn a JPA entity into a response record, and you will see where that mapping belongs.
Why map by hand
A JPA entity carries persistence concerns: lazy associations, a no-argument constructor, and often fields that clients should never see, such as password hashes. If a controller returns the entity, Jackson serializes whatever it can reach. That can leak fields. It can also trigger lazy loading outside a transaction, or recurse through a bidirectional relationship.
A response record fixes the shape of the payload. The mapping step is the one place where you decide which entity fields go out.
A static factory method
The simplest mapping is a static from method on the record. The record declares what the API exposes, and the factory copies those values from the entity.
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 entity has more fields than the record, for example a password hash. They are not copied, so they cannot appear in the JSON.
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private String email;
private String passwordHash;
protected User() {
}
public User(String name, String email, String passwordHash) {
this.name = name;
this.email = email;
this.passwordHash = passwordHash;
}
public Long getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
}Where the mapping runs
Call the factory in the service layer, inside the transaction, and return the record to the controller. By then the data is plain values, so nothing lazy can fail later during serialization.
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
class UserService {
private final UserRepository repository;
UserService(UserRepository repository) {
this.repository = repository;
}
@Transactional
public UserResponse create(CreateUserRequest request) {
User saved = repository.save(new User(request.name(), request.email(), "n/a"));
return UserResponse.from(saved);
}
@Transactional(readOnly = true)
public List<UserResponse> findAll() {
return repository.findAll().stream().map(UserResponse::from).toList();
}
}The UserResponse::from method reference works with streams, so mapping a list takes one line.
Nested data and associations
When the entity has associations, map them explicitly and choose how much to include. Suppose an Order has a customer and a list of lines.
import java.util.List;
public record OrderResponse(Long id, String customerName, List<String> itemNames) {
public static OrderResponse from(Order order) {
return new OrderResponse(
order.getId(),
order.getCustomer().getName(),
order.getLines().stream().map(OrderLine::getProductName).toList());
}
}Flatten when the client does not need the nested object. Use a nested record when it does. Either way, touch lazy associations only inside the transactional service method.
Common errors
- Mapping in the controller. The persistence session may be closed by then, which raises
LazyInitializationExceptionwhen a lazy association is read. - Returning the entity "just for now". Fields added to the entity later appear in the API without anyone deciding that.
- Null entities.
UserResponse.from(null)throwsNullPointerExceptionatuser.getId(). Handle the missing case first, for example withorElseThrowon theOptional. - N+1 queries. Reading
order.getLines()for every order in a list issues one query per order. Use a fetch join or an entity graph in the repository query.
Factory method or mapping library
| Approach | Strength | Cost |
|---|---|---|
| Static `from` method | Plain Java, easy to debug, compiler checks field names | Written by hand for each DTO |
| Mapping library such as MapStruct | Less repetitive code for large models | Extra dependency and generated code to learn |
For most small and medium APIs, the factory method is enough. Consider a library when you have many DTOs with mostly identical field names.
Exercise
A controller method calls repository.findById(id).map(UserResponse::from) after the service's transaction has ended, and the entity has a lazy roles collection that from reads. What error can occur, and where should the mapping happen instead?
Show answer
Reading the lazy roles collection outside a transaction can throw LazyInitializationException. Do the mapping in a @Transactional service method, and return the UserResponse record to the controller.
Exercise
Why does a response record that has no passwordHash component protect that field, even if the entity has it?
Show answer
The from factory copies only the components the record declares. Jackson serializes the record, not the entity, so any field not in the record cannot appear in the JSON.