Video in progress

Strong Junior 🐻 Hibernate and JPA

If you need only a field or two, how do you use a projection instead of the entity?

In JPQL you read directly into a DTO or record with select new, and in Spring Data into an interface or record projection. Only the columns you need are SELECTed, the objects don't land in the persistence context, and there is no dirty checking.

📖 Answer

With a record:

public record OrderRow(Long id, String customerName, BigDecimal total) { }

@Query("""
       select new com.shop.dto.OrderRow(o.id, c.name, o.total)
       from Order o join o.customer c
       where o.status = :status
       """)
List<OrderRow> findRows(@Param("status") Status status);

Inside select new you write the class's fully qualified name (some Hibernate 6.x versions also accept the short name, but don't rely on it).

A Spring Data interface projection:

interface ProductName {
    Long getId();
    String getName();
}

List<ProductName> findByCategoryId(Long categoryId);

Why this is useful: for a list page there's no need to load a 30-column entity and its @ManyToOne associations. Less data comes over the network, you save memory and the flush-time check, and there is no risk of LazyInitializationException.

Be careful: in an interface projection, if you use SpEL with @Value("#{...}") or ask for a nested association, Spring Data may load the whole entity. Check the SQL log.

A projection is not for modification: if you need to update the data, work with the entity.