Sub topic 3
Mapping Entities to Response Records
Assume Java 17+, basic Spring Boot controllers, JPA entities, JSON, and HTTP response bodies.
Mapping entities to response records
A persistence entity represents database state. A response DTO represents the public API shape. Keep them separate so database fields, relationships, and internal changes do not become accidental API fields.
Use a static factory method to make the mapping explicit:
public record UserResponse(Long id, String name, String email) {
public static UserResponse from(User user) {
return new UserResponse(user.getId(), user.getName(), user.getEmail());
}
}A controller or service can return UserResponse, rather than exposing User.
Returning records from Spring Data queries
Spring Data JPA can create a record projection. A projection is an object containing only selected query results.
public record UserSummary(Long id, String name) {
}
public interface UserRepository extends JpaRepository<User, Long> {
List<UserSummary> findByActiveTrue();
}Spring Data maps the selected entity properties to the record constructor. Ensure constructor parameter names are available to the compiler, commonly by compiling with -parameters.
Shallow immutability and limits
A record’s fields cannot be reassigned after construction, but this immutability is shallow. A mutable field can still change:
public record OrderResponse(List<String> itemIds) {
}The list can be changed unless the constructor copies it. Records also cannot extend another class, and JPA entities normally cannot be records because JPA expects a no-argument constructor, proxying, and mutable entity state.
Renaming and shaping JSON
Jackson uses record components as JSON properties. An annotation can rename or hide a property:
public record UserResponse(
Long id,
@JsonProperty("display_name") String name,
@JsonIgnore String internalNote) {
}The Java component remains name, while JSON uses display_name. internalNote is omitted.
Testing record DTOs with `@JsonTest`
A JSON slice test checks serialization without starting the whole application:
@JsonTest
class UserResponseJsonTest {
@Autowired
JacksonTester<UserResponse> json;
@Test
void serializesDisplayName() throws Exception {
var response = new UserResponse(1L, "Ada", "private");
assertThat(json.write(response))
.extractingJsonPathStringValue("$.display_name")
.isEqualTo("Ada");
}
}Exercise
Why should a response record usually be mapped from an entity instead of returning the entity directly?
Show answer
Mapping controls the public JSON shape and prevents internal persistence fields or relationships from leaking into the API.