Sub topic 9
Reading only what you need with DTO projections
This chapter assumes you know JPA entity mapping, Spring Data repositories, and basic SQL joins and GROUP BY. It uses the Author and Book model from the earlier chapters.
Why projections avoid N+1
Every fix so far still loads entities. Entities enter the persistence context, get dirty-checked, and carry lazy associations that can trigger more queries. Often a screen needs two values, such as an author's name and the number of books. Loading every Book row just to call size() wastes memory and time.
A DTO projection (data transfer object projection) asks the database for only the columns you need and maps each row to a plain object. No entity is created, so there is nothing to lazy-load. The N+1 pattern cannot occur.
A constructor expression
A JPQL constructor expression builds the DTO inside the query. The target here is a Java record:
public record AuthorBookCount(String name, Long bookCount) {}
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.
The query issues one SQL statement with a join and an aggregate. The left join keeps authors with no books, and count(b) returns 0 for them. count returns a Long, so the record component must be Long, not int.
Compare this with the N+1 version from earlier:
| Approach | Statements for N authors | Entities loaded |
|---|---|---|
| `findAll()` then `getBooks().size()` | 1 + N | Authors and all their books |
| `JOIN FETCH` | 1 | Authors and all their books |
| DTO projection with `count` | 1 | None |
JOIN FETCH fixes the statement count but still loads every book. The projection fixes both.
What you give up
- No managed entities. Changes to a DTO are not saved. A projection is for reading only. To update data, load the entity.
- Query per use case. Each shape of result needs its own query and DTO. This is more code than reusing one entity everywhere.
- Constructor and type matching. If the constructor arguments do not match the selected types, the application fails at startup when Spring validates the query, or at runtime, depending on the setup. A mismatch is typically a
Longversusintproblem.
Checking the result
Turn on SQL logging, as covered earlier, and call findAuthorBookCounts(). You should see one select containing left join and group by. If you see several statements, something else is loading entities, such as a caller that fetches Author objects after the projection.
When to choose a projection
Use a projection when the caller only reads data, needs a few columns, or needs aggregates such as counts and sums. Use JOIN FETCH or an entity graph when you need full entities, for example to modify them.
Exercise
A screen lists each author's name and the number of books. A teammate fixes N+1 with select distinct a from Author a join fetch a.books and calls getBooks().size(). The statement count is now 1. Why might a DTO projection still be the better choice, and what must the left join do in the projection query?
Show answer
The join fetch loads every book row into the persistence context just to count them, which costs memory and entity construction time. The projection runs a count aggregate in the database and returns only the name and number. The left join keeps authors that have no books, which then report a count of 0. With an inner join they would disappear from the result.