Sub topic 8
Returning records from Spring Data queries
This chapter assumes you can write a Spring Data JPA repository and that you know what a record is. Earlier chapters showed how to map an entity to a response record by hand with a static factory method. That approach loads the whole entity from the database and then copies a few fields. For read-heavy endpoints, you can often skip that step. Spring Data can build the record directly from the query result.
Why project into a record
A projection is a query result that contains only some of an entity's data. When a list endpoint needs only id and name, loading a full User has three costs:
- The database returns every column, including large or rarely used ones.
- Hibernate creates a managed entity per row and tracks it in the persistence context.
- You still have to map each entity to a DTO afterwards.
A record projection removes all three. Spring Data generates a query that selects only the properties named by the record's components. It calls the record's constructor for each row. The result is a plain, unmanaged, immutable object.
Spring Data supports three projection styles. Records fall under the class-based style, also called a DTO projection.
| Style | Result type | How it is built | Notes |
|---|---|---|---|
| Interface-based, closed | Interface with getters | Proxy over the tuple | Selects only the declared getters |
| Interface-based, open | Interface with `@Value` SpEL | Proxy over the full entity | Loads the whole entity |
| Class-based (DTO) | Class or record | Constructor call | Selects only constructor parameters |
Records suit the class-based style well. Their canonical constructor is the only constructor by default. Their component names are kept in the class file, so Spring Data can match columns to parameters without extra compiler flags.
The basic setup
The examples below use a small User entity. It is not a record, because records cannot be JPA entities (see the limits section below).
package com.example.users;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private boolean active;
protected User() {
}
public User(String name, String email, boolean active) {
this.name = name;
this.email = email;
this.active = active;
}
public Long getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
public boolean isActive() { return active; }
}The projection record lists only the properties you want back:
package com.example.users;
public record UserSummary(Long id, String name) {
}The repository declares a derived query whose return type is the record instead of User:
package com.example.users;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
List<UserSummary> findByActiveTrue();
}Spring Data still parses findByActiveTrue against the User entity, because the repository is declared for User. The where active = true clause comes from the method name. The select clause comes from the return type. Spring Data sees that UserSummary is not the domain type, treats it as a projection, and selects id and name only.
Each record component name must match a property name on the entity. If you declare String fullName and User has no fullName property, the query fails when the repository is created or called. The failure is not silent.
How the result is built
For a class-based projection, Spring Data inspects the type's constructor. It reads the parameter names, builds a query that selects those properties, and then invokes the constructor with the values from each row. Records make this reliable. Ordinary classes need the -parameters compiler flag to expose parameter names, but record component names are always available.
Spring Data needs one constructor to call:
- A record with only its canonical constructor works with no extra setup.
- If you add a second constructor to a record, Spring Data cannot decide which one to use. Mark the intended one with
@PersistenceCreatorfromorg.springframework.data.annotation. - A compact canonical constructor still counts as the canonical constructor. Normalization or checks you wrote there run on every row.
That last point matters. If your compact constructor throws on bad data, a single bad row makes the whole query fail. Keep checks in projection records minimal, and leave strict validation for request DTOs.
Paging, sorting, and dynamic projections
Projection return types work with the usual repository features. A Page of records needs no special handling.
Page<UserSummary> findByNameContainingIgnoreCase(String fragment, Pageable pageable);Spring Data runs the page query with the projected select clause and a separate count query. Sorting through Pageable uses entity property names, not record component names. They are usually the same, but if you ever rename a component, the sort property still refers to the entity.
A dynamic projection lets the caller choose the result type per call. Declare a generic method with a Class<T> last parameter.
<T> List<T> findByEmailEndingWith(String suffix, Class<T> type);Callers choose the shape:
List<UserSummary> summaries = repository.findByEmailEndingWith("@example.com", UserSummary.class);
List<User> entities = repository.findByEmailEndingWith("@example.com", User.class);Use this when two endpoints need the same filter but different fields. It avoids duplicating the method name with two return types, which Java does not allow.
Writing the query yourself with @Query
When a derived method name becomes unwieldy, you can write JPQL. For a record result, use a constructor expression. The class name must be fully qualified.
package com.example.users;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface UserQueryRepository extends JpaRepository<User, Long> {
@Query("""
select new com.example.users.UserSummary(u.id, u.name)
from User u
where u.active = true
order by u.name
""")
List<UserSummary> findActiveSummaries();
}The constructor expression is resolved by Hibernate, not by Spring Data's projection support. Two consequences follow:
- The argument order and types in
new ...(...)must match the record's canonical constructor exactly. A mismatch fails at startup, when Hibernate validates the query. - Renaming or moving the record breaks the string. The compiler does not check it, so a test that calls the method is the only safety net. A repository test appears later in this chapter.
You can also select into a record with aliases, such as select u.id as id, u.name as name from User u. Spring Data matches aliases to constructor parameters for class-based projections in recent versions. The new expression is the more widely understood form, so it is the safer choice if your team supports several Spring Boot versions.
Joins and nested data
Class-based projections are flat. A record that contains another record or a collection, such as OrderSummary(Long id, CustomerSummary customer), cannot be filled by a derived query. Spring Data does not build nested constructors from joined rows.
You have three options:
- Flatten the record:
OrderSummary(Long id, String customerName), and selecto.customer.namein a JPQL constructor expression. - Use a closed interface projection, which supports nested interfaces.
- Load the entities with a fetch join and map them with a static factory method, as in the earlier chapter on entity mapping.
Choose flattening when the data is small and read-only. Choose entity loading when the same data is also needed for updates in the same transaction.
What you give up
Projected records are not entities. Know what that means before using them everywhere.
- They are not managed. Changing a record does nothing, and a record is immutable anyway. To update a user, load the
Userentity, change it, and let the transaction commit. - There is no lazy loading. Everything the record needs must be in the query.
- They bypass entity-level logic. Getters on the entity that compute values do not run, because Spring Data reads properties and not your methods. If a response needs a computed field, calculate it in the record's constructor or in a mapper from fields you did select.
- The query shape is fixed at the repository method. An endpoint that later needs one more field means editing the record, which changes the query for every caller of that method.
Choosing between projection and entity mapping
| Situation | Prefer |
|---|---|
| Read-only list or search endpoint with a few fields | Record projection |
| Response needs nested objects or collections | Entity load plus `from(...)` mapping |
| The same data will be modified in the same transaction | Load the entity |
| Same filter, several response shapes | Dynamic projection with `Class<T>` |
| Native SQL, reporting views | Interface projection or manual mapping |
A projection is a performance and simplicity tool for reads. It is not a replacement for response DTOs in general. The projection record in the repository can still be converted to a response record in the service if the API contract differs from the query shape. Often it does not, and returning the same record from the controller is acceptable for simple endpoints. If you do that, remember that the projection record is now part of your public API, and changing it changes your JSON.
Testing the repository
Test the query, not only the record. A @DataJpaTest starts only the JPA layer with an in-memory database, which is enough to check that the select clause and constructor mapping work.
package com.example.users;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
@DataJpaTest
class UserRepositoryTest {
@Autowired
private UserRepository repository;
@Test
void returnsOnlyActiveUsersAsSummaries() {
repository.save(new User("Ada", "[email protected]", true));
repository.save(new User("Bob", "[email protected]", false));
List<UserSummary> result = repository.findByActiveTrue();
assertThat(result)
.extracting(UserSummary::name)
.containsExactly("Ada");
}
}This test needs an in-memory database such as H2 on the test classpath. It fails if a record component does not match an entity property, which is the most common mistake with projections.
Common errors
- A component name does not match an entity property. The error mentions an unknown property or a failed query derivation. Rename the component or use a
@Querywith explicit aliases. - A type mismatch. A record with
int idwhen the entity usesLongcan fail with a null value (primitives cannot hold null) or a conversion error. Use the same wrapper type as the entity, unless the column is guaranteed non-null. - More than one constructor. Spring Data picks none, or the wrong one. Add
@PersistenceCreatorto the one you want, or keep only the canonical constructor. - A wrong package in a constructor expression. The query fails at startup with an unknown class message. Keep the string in sync with the record's package, and keep the repository test.
- Expecting entity behavior. Code that calls a record and expects lazy loading or dirty checking fails silently or throws, because there is no persistence context behind the object.
Exercise
A repository declares List<UserSummary> findByActiveTrue();, where UserSummary is record UserSummary(Long id, String fullName), and the User entity has id and name properties but no fullName. What happens, and how do you fix it without renaming the entity property?
Show answer
Spring Data cannot map the fullName component to an entity property, so the query fails when the repository is created or first used. Write a JPQL query with a constructor expression instead, for example @Query("select new com.example.users.UserSummary(u.id, u.name) from User u where u.active = true"). The constructor argument order matters, and the component names no longer need to match entity property names.
Exercise
A response needs an order's id and its customer's name and email. Why can't record OrderView(Long id, CustomerView customer) be returned from a derived query, and what are two ways to get the data?
Show answer
Class-based projections are flat. Spring Data does not build a nested record from joined rows. Either flatten the record to OrderView(Long id, String customerName, String customerEmail) and select the fields in a JPQL constructor expression, or load the Order entity with a fetch join and map it with a static factory method.