Sub topic 8
Returning Records from Spring Data Queries
This chapter assumes you know how to write a Spring Data JPA repository and have an entity such as User. It also assumes you read the earlier chapter on mapping entities to response records. Here you skip the entity-to-record copy and have the repository return records directly.
Why project into a record
Loading a full User entity to show an id and a name wastes work. Hibernate reads every column, tracks the entity in the persistence context, and may expose lazy associations to accidental loading. A projection asks the database for only the columns you need. A record is a good target because it is immutable and has no persistence behavior.
Spring Data calls a record used this way a class-based projection, sometimes called a DTO projection.
A derived query that returns a record
The entity below is the minimum needed to run the example.
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 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; }
}Now declare the record and the repository. The only change from an ordinary derived query is the return type.
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public record UserSummary(Long id, String name) {
}
public interface UserRepository extends JpaRepository<User, Long> {
List<UserSummary> findByActiveTrue();
}Spring Data sees that UserSummary is not the entity type. It reads the constructor parameters and generates a query that selects only id and name, filtered by active = true. The SQL looks like select u.id, u.name from users u where u.active = true. It does not select the email column.
How the mapping works
- Spring Data matches record component names to entity property names.
idandnamein the record must exist onUserwith compatible types. - The record's canonical constructor is the one used. Keep it to a single constructor so there is no ambiguity.
- The returned objects are plain records. They are not managed by the persistence context, so changing one has no effect on the database.
- Class-based projections are flat. A record component that is itself a record (a nested projection) is not supported. Use an interface projection or a manual mapping for nested shapes.
Writing the query yourself with @Query
When the derived method name would get long, or you need a join, write JPQL with a constructor expression. The class name must be fully qualified.
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface UserQueries extends JpaRepository<User, Long> {
@Query("""
select new com.example.users.UserSummary(u.id, u.name)
from User u
where u.name like concat(:prefix, '%')
""")
List<UserSummary> findSummariesByNamePrefix(@Param("prefix") String prefix);
}The argument order in new ... must match the record's component order, and the types must match as well. Replace com.example.users with your own package.
Choosing the projection per call
If one query should feed more than one DTO, declare a dynamic projection. The caller passes the record type.
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserLookup extends JpaRepository<User, Long> {
<T> List<T> findByActiveTrue(Class<T> type);
}users.findByActiveTrue(UserSummary.class) returns summaries. users.findByActiveTrue(User.class) returns full entities.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Startup fails with a message that a property is not found on `User` | A record component name differs from the entity property | Rename the component, or alias the column in `@Query` |
| `Could not instantiate` or a constructor mismatch error at startup | Constructor expression argument types or order do not match the record | Match the order and types of the record components |
| A nested record component stays null or the query fails | Class-based projections do not support nesting | Flatten the record or map manually |
| Lazy collection values are missing | A projection reads columns, not object graphs | Select the needed columns in `@Query`, or fetch with a join |
When to prefer a record over the alternatives
Use a record projection when the result is small, flat, and goes straight to the API layer. Use from(User) mapping when the response needs logic that depends on several entity fields or associations. Keep the repository return type as the entity when the caller will modify and save it.
Exercise
A repository declares List<UserSummary> findByActiveTrue();, where UserSummary is record UserSummary(Long id, String name). A teammate adds a third component, String phone, but User has no phone property. What happens, and how can you fix it?
Show answer
The application fails to start, or the query fails, because Spring Data cannot map phone to a property on User. Add a phone property to the entity, remove the component from the record, or write an @Query with a constructor expression that supplies the value, for example from a joined table.