Sub topic 9
Reading only what you need with DTO projections
This chapter assumes you know basic JPA mapping, Spring Data JPA repositories, JPQL joins, and GROUP BY. It builds on the Author and Book model from earlier chapters, where a lazy @OneToMany collection causes N+1 selects.
Why projections exist
JOIN FETCH, @EntityGraph, and batch fetching all load managed entities. Managed entities carry overhead. Hibernate tracks them in the persistence context, keeps a snapshot of each one for dirty checking, and builds full object graphs. If a screen only needs an author's name and the number of books, loading every Book row is wasted work.
A DTO projection (data transfer object projection) asks the database for only the columns you need and returns plain objects. There are no entities, no proxies, and no lazy loading. Because nothing is lazy, the N+1 problem cannot happen.
The problem we want to remove
Recall the service from the N+1 chapter:
@Transactional(readOnly = true)
public List<String> authorSummaries() {
return authorRepository.findAll().stream()
.map(a -> a.getName() + ": " + a.getBooks().size())
.toList();
}This issues one query for the authors and one more per author to initialize books. The code only needs a name and a count. Loading entire Book rows to call size() is the wasteful part.
Constructor expressions in JPQL
A JPQL constructor expression builds a DTO directly in the query. First define the DTO as a Java record:
public record AuthorBookCount(String name, Long bookCount) {}Then write the query in a repository:
public interface AuthorStatsRepository extends JpaRepository<Author, Long> {
@Query("""
select new com.example.AuthorBookCount(a.name, count(b))
from Author a left join a.books b
group by a.id, a.name
""")
List<AuthorBookCount> findAuthorBookCounts();
}Adjust the package name in new com.example.AuthorBookCount(...) to match your project. JPQL needs the fully qualified class name.
Several details matter here:
count(b)returns aLong, so the record component must beLong. A mismatch such asintcauses an error when the query is validated or run.- The constructor arguments must appear in the same order and with compatible types as the record components.
left joinkeeps authors who have no books, and their count is0. An innerjoinwould drop them silently.group by a.id, a.namegroups on the primary key plus the selected column. This is portable across databases that require every non-aggregated column in theGROUP BY.
The generated SQL is a single statement, roughly:
select a.name, count(b.id)
from author a
left join book b on b.author_id = a.id
group by a.id, a.nameUsing it from the service is straightforward:
@Service
public class AuthorStatsService {
private final AuthorStatsRepository repository;
public AuthorStatsService(AuthorStatsRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<String> authorSummaries() {
return repository.findAuthorBookCounts().stream()
.map(r -> r.name() + ": " + r.bookCount())
.toList();
}
}With N authors this runs one statement instead of 1 + N.
Other ways to get a projection
Constructor expressions are not the only option. Spring Data JPA offers more, and each has trade-offs.
| Approach | How it works | Strengths | Limits |
|---|---|---|---|
| Constructor expression in `@Query` | JPQL calls the DTO constructor | Explicit, works with joins and aggregates, checked against the query | Verbose, ties the query to a class name |
| Class-based projection (derived query) | Spring Data matches constructor parameter names to properties | No `@Query` needed for simple cases | Only direct properties of the root entity; no aggregates |
| Interface-based projection | Spring Data returns a proxy that implements the interface | Very little code | Closed projections select only needed columns; open projections (using SpEL) load the whole entity |
| Tuple or `Object[]` | Raw values returned in order | No class needed | Easy to break, no type safety |
A class-based projection for a simple case looks like this:
public record AuthorName(Long id, String name) {}
public interface AuthorNameRepository extends JpaRepository<Author, Long> {
List<AuthorName> findAllBy();
}Spring Data sees that the return type is a record, reads its constructor, and selects only id and name. This works because the properties belong directly to Author.
An interface-based projection for the same data:
public interface AuthorNameView {
Long getId();
String getName();
}
public interface AuthorViewRepository extends JpaRepository<Author, Long> {
List<AuthorNameView> findAllBy();
}Projections across a relationship
Often you want fields from both sides of an association. Use a join in the query and list scalar fields from each entity:
public record BookRow(String title, String authorName) {}
public interface BookRowRepository extends JpaRepository<Book, Long> {
@Query("""
select new com.example.BookRow(b.title, a.name)
from Book b join b.author a
""")
List<BookRow> findBookRows();
}Book.author is a lazy @ManyToOne. Because the query selects a.name through an explicit join, no proxy is created and no extra query runs. This is also a good fix when you only need one column from the parent.
What you give up
A projection is not free of cost. Know these trade-offs before choosing it.
- Not managed. DTOs are not tracked by the persistence context. Changes to them are never flushed.
- Not cached by the persistence context. Repeating the query repeats the SQL. Entities loaded twice in one transaction would be served from the context the second time, though a JPQL query still hits the database.
- One shape per query. Each screen or use case tends to get its own DTO and query. That is more code than reusing one entity graph.
- Flat results for collections. A constructor expression cannot return a DTO that contains a nested list of child DTOs. A join over a collection returns one row per child, so you must either accept flat rows or group them in Java.
Here is the grouping approach when you need a nested shape:
public record BookTitleRow(Long authorId, String authorName, String title) {}
public record AuthorWithTitles(String name, List<String> titles) {}
public interface BookTitleRepository extends JpaRepository<Book, Long> {
@Query("""
select new com.example.BookTitleRow(a.id, a.name, b.title)
from Book b join b.author a
order by a.id
""")
List<BookTitleRow> findTitleRows();
}@Transactional(readOnly = true)
public List<AuthorWithTitles> authorsWithTitles() {
Map<Long, List<BookTitleRow>> grouped = bookTitleRepository.findTitleRows().stream()
.collect(Collectors.groupingBy(BookTitleRow::authorId, LinkedHashMap::new, Collectors.toList()));
return grouped.values().stream()
.map(rows -> new AuthorWithTitles(
rows.get(0).authorName(),
rows.stream().map(BookTitleRow::title).toList()))
.toList();
}Because the query starts from Book with an inner join, authors without books do not appear. Use a query starting from Author with left join if you need them, and handle the null title that results.
Notice that this approach needs no collection fetch join. It avoids the pagination and multiple-bag problems that the next chapter covers. The cost is that you assemble the structure yourself.
How a projection reaches the database
The following diagram contrasts the entity path with the projection path.
Verifying the result
Do not assume a projection did what you intended. Turn on the logging settings from the detection chapter and read the SQL:
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.SQL=DEBUGCheck three things. The select list contains only the columns you expect. There is a single statement per call. No query to the book table appears when you only needed a count. You can also reuse the query-count test pattern from the regression chapter and assert that getPrepareStatementCount() equals 1.
Common mistakes
- Returning an entity from a query that selects a subset of columns, then expecting the other fields to exist. Select into a DTO instead.
- Using
joininstead ofleft joinfor counts, which hides parents with no children. - Mismatching the type of
count(...). It is alwaysLong. - Forgetting the fully qualified class name in a constructor expression.
- Using an open interface projection and assuming it is lightweight.
- Putting a DTO on a write path and expecting changes to persist.
Exercise
A report page lists each author's name and number of books. A teammate proposes @EntityGraph(attributePaths = "books") on findAll() and then calling getBooks().size(). Why might a DTO projection still be a better fit, and which join type should the projection query use so that authors without books still appear?
Show answer
The entity graph fixes the N+1 pattern, but it loads every Book row and builds managed entities just to count them. A projection such as select new com.example.AuthorBookCount(a.name, count(b)) from Author a left join a.books b group by a.id, a.name sends one aggregate query and returns two values per author. It must use left join so that authors with no books are kept, with a count of 0. An inner join would drop them.
Exercise
You declare record AuthorBookCount(String name, int bookCount) and use it in the constructor expression with count(b). What goes wrong, and how do you fix it?
Show answer
JPQL count returns a Long, but the record component is int, so Hibernate cannot find a matching constructor and the query fails. Change the component to Long bookCount.