Video in progress

Strong Middle 🌱 Spring

What do Spring Data projections (interface and DTO) give you?

Instead of the whole entity, you fetch only the columns you need. The query gets lighter, the dirty checking and persistence context overhead goes away, and lazy problems become rarer.

📖 Answer

An interface projection:

public interface ProductCard {
    Long getId();
    String getName();
    BigDecimal getPrice();
}

List<ProductCard> findByCategory(String category);

Spring Data sends select p.id, p.name, p.price from Product p where ..., so only 3 of the 40 columns of the table come back.

A DTO (record) projection:

public record ProductRow(Long id, String name, BigDecimal price) {}

@Query("select new uz.shop.ProductRow(p.id, p.name, p.price) from Product p where p.category = :c")
List<ProductRow> rows(@Param("c") String c);

In Spring Data 3.x it often works even if you just make the record the return type.

A dynamic variant:

<T> List<T> findByCategory(String category, Class<T> type);

An "open" projection (@Value("#{target.name + ' ' + target.surname}")) loads the whole entity, so you lose the benefit. A nested projection (getCustomer().getName()) sometimes fetches more than you expect, so take a look at the SQL in the log.

List pages, reports and API responses are where projections belong. If you need to modify the data, use the entity.