Sub topic 14
Interface and DTO Projections
This chapter assumes you know how to define entities and repositories, write derived queries and @Query methods, and that you understand lazy loading and the N+1 problem from earlier chapters. You should also be comfortable reading basic JPQL and SQL.
Why return less than an entity
A repository method that returns an entity loads every mapped column. It also puts the entity into the persistence context, where Hibernate tracks it for dirty checking. That is the right choice when you plan to change the entity. It is wasteful when you only need to show a list of titles.
A projection is a read-only view of an entity that contains only some of its fields. Spring Data JPA supports three kinds:
- Interface projections, where you declare an interface with getters and Spring creates a proxy.
- Class-based (DTO) projections, where you declare a class or record with a constructor.
- Dynamic projections, where the caller chooses the projection type.
The examples use the Book and Author entities from earlier chapters. Book has id, title, publishedYear and a lazy author. Author has id and name.
Interface projections
Closed projections
A closed projection declares getters whose names match entity properties.
public interface BookSummary {
Long getId();
String getTitle();
}Return it from a repository method:
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BookSummaryRepository extends JpaRepository<Book, Long> {
List<BookSummary> findByPublishedYearGreaterThanEqual(int year);
}Because every getter maps to a property, Spring Data knows exactly which columns are needed. With derived queries, Hibernate selects only id and title. The returned objects are proxies backed by a tuple, not managed entities. Changing them does nothing, since they have no setters and no tracking.
Nested projections
A getter can return another projection interface. This lets you reach into an association.
public interface BookWithAuthor {
String getTitle();
AuthorName getAuthor();
interface AuthorName {
String getName();
}
}For a nested projection, Spring Data joins the association. Only the first level of nesting is trimmed to selected columns. Deeper nesting can fall back to loading whole entities, so check the generated SQL when you nest more than one level.
Open projections
An open projection uses @Value with a SpEL expression to compute a value.
import org.springframework.beans.factory.annotation.Value;
public interface BookLabel {
@Value("#{target.title + ' (' + target.publishedYear + ')'}")
String getLabel();
}The expression refers to the full entity as target. Spring Data therefore has to load the whole entity before it can evaluate the expression. An open projection saves no columns. Use it only when the convenience matters more than the query cost.
If you want computed values without losing the column savings, put a default method on the interface and keep the underlying getters closed:
public interface BookLabelClosed {
String getTitle();
int getPublishedYear();
default String getLabel() {
return getTitle() + " (" + getPublishedYear() + ")";
}
}This stays closed, because only the abstract getters are inspected.
DTO projections
A DTO projection returns instances of a concrete class. A Java record is a good fit, because it is immutable and has a canonical constructor.
public record BookDto(String title, int publishedYear) {
}import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BookDtoRepository extends JpaRepository<Book, Long> {
List<BookDto> findByTitleContainingIgnoreCase(String text);
}Spring Data matches the constructor parameter names to entity properties, so the parameter names must be available at runtime. Records always keep them. For a regular class, compile with -parameters. Spring Boot's Maven and Gradle plugins configure this for you.
DTOs in `@Query`
With JPQL you can build the DTO yourself using a constructor expression:
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface BookReportRepository extends JpaRepository<Book, Long> {
@Query("""
select new com.example.catalog.AuthorBookCount(a.name, count(b))
from Author a left join a.books b
group by a.name
""")
List<AuthorBookCount> countBooksPerAuthor();
}package com.example.catalog;
public record AuthorBookCount(String authorName, long bookCount) {
}The constructor expression needs the fully qualified class name. The argument types must match the constructor: count returns Long, so the record uses long or Long. A mismatch fails when the application starts or when the query first runs.
Projections on native queries
Native queries cannot use constructor expressions. Interface projections work with them, but the column aliases must match the getter names:
@Query(value = "select b.title as title, b.published_year as publishedYear from books b",
nativeQuery = true)
List<BookDto2> findAllNative();Here BookDto2 would be an interface with getTitle() and getPublishedYear(). Without the aliases, the getters return null.
Dynamic projections
A method can take a Class<T> parameter, so each caller picks its own shape:
import java.util.List;
import java.util.Optional;
public interface BookLookupRepository extends JpaRepository<Book, Long> {
<T> Optional<T> findById(Long id, Class<T> type);
<T> List<T> findByPublishedYear(int year, Class<T> type);
}Calling findByPublishedYear(1974, BookSummary.class) returns summaries. Calling it with Book.class returns full entities. This avoids a separate method for every shape.
Comparing the options
| Feature | Closed interface | Open interface | DTO class or record | Entity |
|---|---|---|---|---|
| Selects only needed columns | Yes | No | Yes | No |
| Computed values | Default methods | SpEL | Constructor or methods | Methods |
| Managed and dirty-checked | No | No | No | Yes |
| Works with native queries | Yes, with aliases | Limited | No for constructor expressions | Yes |
| Can be written in a `@Query` constructor expression | No | No | Yes | No |
Projections and the persistence context
None of the projections above are managed entities. Two consequences follow.
- You cannot change a projection and expect the database to change. To update data, load the entity inside a transaction.
- A projection does not trigger lazy loading, because it holds plain values. This makes projections a clean fix for
LazyInitializationExceptionin read-only views. Fetch exactly the fields the view needs, and the session can close safely.
Projections also address N+1 selects for read-only screens. A nested projection or a DTO query with a join reads the author's name in the same statement as the book.
@Query("select new com.example.catalog.BookRow(b.title, a.name) from Book b join b.author a")
List<BookRow> findAllRows();package com.example.catalog;
public record BookRow(String title, String authorName) {
}Common errors
- Projection getter returns
null. The getter name does not match a property or alias. Check the capitalization:getPublishedYear()maps topublishedYear. - All columns are still selected. The projection is open, or it is nested more than one level deep. Remove
@Valueor check the generated SQL by enablingspring.jpa.show-sql=true. No converter foundorFailed to instantiate. A DTO class has several constructors, or its constructor parameters do not match the property names. Keep one canonical constructor.- Constructor expression fails with
Unable to locate appropriate constructor. The types in theselect newclause do not match the constructor. Check aggregate return types such ascount, which returnsLong. - Expecting changes to be saved. Projections are read-only. Load the entity to modify it.
Choosing a projection
- Use an entity when you will modify the data in the same transaction.
- Use a closed interface projection for simple read-only views of a few fields. It needs the least code.
- Use a DTO record when you need a stable API type, such as a REST response, or a query with aggregates and joins.
- Use a dynamic projection when many callers need the same query but different shapes.
- Avoid open projections on large result sets, because they load whole entities.
Exercise
A repository method returns List<BookLabel>, where BookLabel has one getter annotated with @Value("#{target.title.toUpperCase()}"). A colleague expects the SQL to select only the title column. Is that correct, and how would you change the projection so that it does?
Show answer
No. The @Value expression uses target, which is the whole entity, so the projection is open and Spring Data loads every column. To select only title, make the projection closed. Declare String getTitle(); as an abstract getter and add a default String getTitleUpper() method that calls getTitle().toUpperCase(). Only the abstract getters are inspected, so the query selects just title.
Exercise
You write @Query("select new com.example.catalog.AuthorBookCount(a.name, count(b)) ..."), but AuthorBookCount is declared as record AuthorBookCount(String authorName, int bookCount). The query fails. Why, and what is the fix?
Show answer
JPQL count returns Long, and the record constructor expects int, so no matching constructor is found. Change the component to long (or Long).