Sub topic 14
Interface and DTO projections
This chapter assumes you can write a repository with derived queries and understand how Book and Author are mapped, as in the earlier chapters. A projection returns only some fields of an entity, so the query does not load whole entities when you only need a few columns.
Why project
findByPublishedYearGreaterThanEqual returns full Book entities. Each one is managed by the persistence context, and each carries a lazy author reference. A list screen that shows only titles and years does not need any of that. A projection narrows the select list and returns plain read-only objects.
Interface projections
Declare an interface with getters for the properties you want. Spring Data creates a proxy for each row.
public interface BookSummary {
String getTitle();
int getPublishedYear();
}import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BookRepository extends JpaRepository<Book, Long> {
List<BookSummary> findByPublishedYearGreaterThanEqual(int year);
}The interface is closed because every getter maps to an entity property. For a closed projection, Spring Data selects only title and published_year.
You can also nest a projection for an association:
public interface BookWithAuthor {
String getTitle();
AuthorName getAuthor();
interface AuthorName {
String getName();
}
}Nested projections for to-one associations work, but check the generated SQL. Depending on the query, the provider may join the author or load more columns than you expect.
DTO projections
A DTO (data transfer object) is an ordinary class or record. Spring Data matches the constructor parameters to the selected columns by position and name.
public record BookDto(String title, int publishedYear) {
}import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface BookDtoRepository extends org.springframework.data.repository.Repository<Book, Long> {
List<BookDto> findByAuthorName(String name);
@Query("select new BookDto(b.title, b.publishedYear) from Book b where b.publishedYear = :year")
List<BookDto> findDtosByYear(@Param("year") int year);
}In the @Query method, the JPQL constructor expression needs a fully qualified class name unless your provider can resolve the simple name. Use com.example.catalog.BookDto with your own package.
Dynamic projections
One method can serve several shapes if you add a Class<T> parameter.
<T> List<T> findByTitleContainingIgnoreCase(String text, Class<T> type);Call it with BookSummary.class, BookDto.class, or Book.class.
Common errors
- Open projections. A getter annotated with
@Value("#{target.title + ' by ' + target.author.name}")forces Spring Data to load the whole entity. You lose the narrower select. - Property name mismatch. A getter such as
getYear()does not matchpublishedYear, so it returnsnullor fails at startup. Names must match entity properties. - Expecting dirty checking. Projections are not managed entities. Changing one does nothing, and you cannot pass one to
save.
Exercise
A method returns List<BookSummary> where BookSummary has a getter annotated with @Value("#{target.author.name}"). Why does this defeat the purpose of a projection, and how do you fix it?
Show answer
The @Value expression makes the projection open, so Spring Data loads the whole Book entity and then evaluates the expression. To keep a narrow select, replace it with a closed nested projection, such as an AuthorName getAuthor() getter, or use a DTO built by a JPQL constructor expression.