Sub topic 3
Reading Only What You Need with DTO Projections
Assume you know basic Spring Data JPA, JPQL, joins, and entity mappings. A DTO projection returns selected values instead of fully managed entities. It avoids loading relationships that the endpoint does not use.
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();
}This query returns one row per author. It does not create an Author entity or trigger lazy loading of books.
Fetching collections: pagination and multiple bags
A collection fetch join can multiply result rows. Hibernate may also ignore database pagination and paginate in memory. For large pages, first fetch parent IDs with Pageable, then fetch those IDs and their collections in a second query.
Fetching two unordered List collections in one query can cause Hibernate’s multiple-bag problem. Use separate queries, a Set, or a DTO query when the endpoint needs data from both collections.
Choosing a strategy
| Query shape | Suitable choice |
|---|---|
| Full entities and one collection | JOIN FETCH or `@EntityGraph` |
| A few scalar fields or totals | DTO projection |
| Many parents with modest relationships | Batch fetching |
| Large paged collection results | Two-step ID pagination |
Open Session in View and query-count tests
Open Session in View keeps the persistence context open through controller rendering. It can hide accidental lazy loads in serializers. Set spring.jpa.open-in-view=false, then load required data inside a service transaction.
Test query counts so an innocent mapper change cannot restore N+1:
statistics.clear();
authorService.authorSummaries();
assertThat(statistics.getPrepareStatementCount()).isEqualTo(1);JDBC batching and caching
JDBC batching groups inserts or updates into fewer database round trips:
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=trueGenerationType.IDENTITY can prevent insert batching. Sequence-based identifiers usually work better.
A second-level cache helps repeated reads of stable entities. It does not fix a poorly shaped query and can hide excessive reads during testing. Measure SQL first, then cache data with a clear invalidation policy.
Exercise
An endpoint needs only author names and book counts. Which strategy should you choose?
Show answer
Use a DTO projection with an aggregate query. It selects only the required values and avoids loading entities and collections.