Skip to content
javahacks.dev
Hibernate

How to Use DTO Projections With Hibernate and Records

Use DTO projections with Hibernate and Java records: constructor expressions in JPQL, Spring Data interface and class projections, and when to skip entities.

5 min read
Summarize in AI
Flat illustration of an entity class mapped to a database table, with the Hibernate, OpenJDK, MySQL and PostgreSQL logos.

Loading entities to return three fields wastes memory, wastes queries and invites lazy loading bugs. A projection selects exactly what an endpoint needs and hands back a plain object, and Java records are a natural target for it: immutable, compact and free of Hibernate's proxies. This guide shows the four ways to get a projection with Hibernate 7 and Spring Boot 4, compares them with loading entities and lists the pitfalls that show up the first time a query changes. The patterns apply to read paths such as list pages, reports and API responses.

JPQL constructor expression

java
public record AuthorSummary(Long id, String name, long bookCount) {}

@Query("""
    select new com.example.AuthorSummary(a.id, a.name, count(b))
    from Author a left join a.books b
    group by a.id, a.name
    """)
List<AuthorSummary> summaries();

Hibernate calls the record's canonical constructor with the selected values. The fully qualified class name is required in new, which is the most common reason this query fails to parse. The parameter types must match the select list. count returns a Long, so a long component works through unboxing, while a mismatch such as an int for a Long column fails with a message about no matching constructor. The aggregate is computed in the database, which is the main gain: the books are never loaded into memory just to be counted.

Spring Data class projection

java
interface AuthorRepository extends JpaRepository<Author, Long> {

    List<AuthorSummary> findByCountry(String country);
}

When the return type is a class or record with a matching constructor, Spring Data selects only those columns. The derived query uses the component names as property paths, so a record with name and email components issues select a.name, a.email from Author a where a.country = ?1. This is the lowest-ceremony form, and it reads well, but it limits you to what the derived-query grammar can express. Anything with an aggregate or a join needs an explicit @Query.

Interface projections

java
interface AuthorView {
    String getName();
    String getEmail();
}

List<AuthorView> findByCountry(String country);

Spring creates proxies backed by a tuple. They work, but a proxy is harder to debug and to serialise than a record, and its toString and equals are not what you expect. Prefer records unless you need open projections with a SpEL expression such as @Value("#{target.first + ' ' + target.last}"), and know that an open projection loads the whole entity, which defeats the purpose.

Dynamic and native cases

For native queries and queries built at run time, map the tuple yourself.

java
List<AuthorSummary> rows = session.createNativeQuery("""
        select id, name, 0 as book_count from author
        """, Tuple.class)
    .getResultList().stream()
    .map(t -> new AuthorSummary(t.get("id", Long.class), t.get("name", String.class), 0))
    .toList();

Reading values by alias and expected type keeps the mapping explicit, and a changed column fails at the mapping line rather than deep in a view. For a Criteria query, CriteriaBuilder.construct does the same job as the constructor expression without a string.

Why projections help

EntityDTO projection
Columns loadedAllChosen
Managed by the sessionYes, and dirty-checkedNo
Lazy loadingPossible, so N plus 1Impossible
Safe to serialiseRiskyYes

A projection removes whole classes of problems. Nothing can lazily load, so there is no N plus 1 and no LazyInitializationException; nothing is tracked, so the persistence context stays small and flushes cost nothing; and sensitive columns never reach the controller, which makes accidental exposure in JSON impossible. The entity route has its own remedies, described in N plus 1 and batch fetching, but the best fix for a read-only endpoint is not to load the graph at all.

Reading the SQL

Turn on SQL logging and confirm what the projection actually sent. A constructor expression should produce one select with only the listed columns. If you see a select * equivalent followed by per-row queries, the repository method is returning an entity or an open projection, and the record is being built afterwards from a loaded entity. Checking this once per new projection takes a minute, and the technique is covered in logging Hibernate SQL and statistics.

When to keep entities

Writes need entities: you load one, change it and let dirty checking flush it. A projection cannot be saved. Use projections for list pages, reports and API responses that need a subset or an aggregate, and entities for commands that modify state. A pattern that works well is to read through projections and write through entities, with the service layer converting between them where an API takes a modification request.

Pitfalls

A mismatch between constructor parameters and the select list fails at startup or at the first call, so cover every projection query with a test. Joining a collection multiplies rows, so a left join to books without a group by returns one summary per book, not per author; group the result or use a separate query. Renaming a record component renames the property path in derived queries, and the failure is a startup error that points at the repository method. And count in a constructor expression returns Long, which will not match an int component.

Pagination and sorting with projections

A projection works with Pageable the same way an entity does, and the result is a Page<AuthorSummary>. Two details matter. Spring derives the count query from the select, and a grouped constructor expression confuses it, so supply countQuery explicitly when the main query has a group by. And sorting by a property that is not in the projection fails, so allow only the properties the record exposes and map the rest to a short whitelist. Together they keep a list endpoint fast on a large table, since the page query touches only indexed columns and returns a handful of rows.

Nested data without loading the graph

A list of authors each with their five most recent titles is the case that tempts people back to entities. Do it in two queries: load the page of authors as a projection, then load the titles for those ids in a second query with where author_id in (:ids), and assemble the nested records in memory. Two small queries are cheaper and more predictable than one join that multiplies rows, and each stays a plain projection.

When projections are not worth it

If an endpoint returns a whole aggregate to be edited and saved, use the entity. A tiny table with five columns gains nothing from a record. Records as a language feature are explained in the records guide, and entity mapping in JPA entity mapping. References: Spring Data projections and the Hibernate query language guide.

Also inJava Core
Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.