How to Use Projections in Spring Data JPA to Fetch Less
Fetch only the columns you need with Spring Data JPA projections: interface and record DTOs, dynamic, nested and open projections, and limits.

Loading an entity loads everything the mapping says: every column, the lazy proxies for associations and an entry in the persistence context for dirty checking. For a list screen that shows a name and a status of five hundred rows, that is mostly waste: wide rows over the wire, objects that are never modified tracked by Hibernate and a temptation for the serialiser to walk into lazy associations. A projection returns only what the caller needs. Spring Data JPA supports several kinds, with different mechanics and different traps. This post shows interface projections, DTO records and classes, dynamic projections, nested projections and the open projections that quietly defeat the purpose, with the SQL each produces, and gives guidance on choosing. The same idea at the Hibernate level is in DTO projections with records, and the query tuning context in the N plus 1 problem and its fixes.
The entity
@Entity
@Table(name = "orders")
public class Order {
@Id @GeneratedValue private Long id;
private String reference;
private String status;
private BigDecimal total;
private Instant placedAt;
@Column(length = 4000)
private String notes;
@ManyToOne(fetch = FetchType.LAZY)
private Customer customer;
@OneToMany(mappedBy = "order")
private List<OrderLine> lines = new ArrayList<>();
// getters omitted
}A list view needs the reference, the status and the total. Loading the whole entity pulls the notes text and sets up proxies for customer and lines.
Interface projections
The simplest form is an interface with getters for the wanted properties. Spring Data creates a proxy that implements it:
public interface OrderSummary {
String getReference();
String getStatus();
BigDecimal getTotal();
}public interface OrderRepository extends JpaRepository<Order, Long> {
List<OrderSummary> findByStatus(String status);
Optional<OrderSummary> findById(Long id); // shadows the CRUD method with a projection return type
}Turn on SQL logging and look at the query for the first method:
select o1_0.reference, o1_0.status, o1_0.total from orders o1_0 where o1_0.status=?Only three columns are selected, and no entity is created. This is a closed projection: every getter matches a property of the entity, so Spring Data knows it can restrict the select. The result objects are lightweight proxies backed by a tuple. Call summary.getReference() and you read a value from the row.
Rules for closed interface projections: getters only, names matching the entity's property names, and no @Value annotations. Add anything else and the behaviour changes, as the open projection section explains.
Records and classes: DTO projections
A class based projection, which includes a Java record, is instantiated through its constructor, with no proxy:
public record OrderRow(String reference, String status, BigDecimal total) {}
public interface OrderRepository extends JpaRepository<Order, Long> {
List<OrderRow> findRowsByStatus(String status);
}For derived query methods, Spring Data maps the record's components to entity properties by name and selects those columns. The result is an immutable DTO that can be used directly in an API response without any proxy or lazy loading concern, which makes records a good default for projections: they are plain data, they serialise predictably and they cannot hold a persistence context reference. The constructor parameter names must be available (the compiler's -parameters flag, on by default in Spring Boot builds) and match entity property names.
For JPQL queries, either use the constructor expression or let the record be inferred from the select aliases:
@Query("select new dev.javahacks.orders.OrderRow(o.reference, o.status, o.total) from Order o where o.status = :status")
List<OrderRow> rowsByStatus(@Param("status") String status);
@Query("select o.reference as reference, o.status as status, o.total as total from Order o where o.placedAt >= :since")
List<OrderSummary> recent(@Param("since") Instant since);The first uses a JPQL constructor expression with the fully qualified class name. The second selects with aliases that match the interface's property names, which is how interface projections work with custom @Query methods: the aliases are the contract, and a mismatch gives null values silently, a common surprise.
Nested projections
A projection can include associated entities' properties. A nested interface describes the association:
public interface OrderWithCustomer {
String getReference();
BigDecimal getTotal();
CustomerInfo getCustomer();
interface CustomerInfo {
String getName();
String getEmail();
}
}List<OrderWithCustomer> findByPlacedAtAfter(Instant since);select o1_0.reference, o1_0.total, c1_0.id, c1_0.name, c1_0.email
from orders o1_0 left join customer c1_0 on c1_0.id=o1_0.customer_id
where o1_0.placed_at>?Spring Data joins the customer and selects only the named columns. The limits: nested projections work for to-one associations; projecting a collection (List<LineInfo> getLines()) triggers loading of the entity, as the generated query cannot flatten a collection into a row, and you are back to full entities and N plus 1. For collections, run a second query keyed by the parent ids, or use a JPQL query that returns flat rows and group them in code.
Dynamic projections
One repository method can return different views, chosen by the caller, by taking the target type as a parameter:
public interface OrderRepository extends JpaRepository<Order, Long> {
<T> List<T> findByStatus(String status, Class<T> type);
}List<OrderSummary> summaries = orders.findByStatus("NEW", OrderSummary.class);
List<OrderRow> rows = orders.findByStatus("NEW", OrderRow.class);
List<Order> entities = orders.findByStatus("NEW", Order.class); // the full entityThis keeps the query definition in one place and lets a screen ask for exactly the shape it needs, avoiding a separate repository method per view. The type must be an interface projection, a DTO class or the entity itself.
Open projections and why to avoid them
If a getter in an interface projection uses a @Value annotation with a SpEL expression, the projection becomes open:
public interface OrderLabel {
@Value("#{target.reference + ' (' + target.status + ')'}")
String getLabel();
}target is the underlying object, so Spring Data cannot know which properties the expression needs, and loads the full entity to evaluate it. The query selects every column, and the benefit of projecting disappears; the code gives no sign of it. Compute derived values in a default method on the interface instead, where the properties it uses are visible getters:
public interface OrderLabel {
String getReference();
String getStatus();
default String getLabel() {
return getReference() + " (" + getStatus() + ")";
}
}A closed projection with a default method keeps the narrow query. Check the SQL log whenever you add a projection, since the difference between closed and open is invisible in the Java.
Projections and the persistence context
A projection is not an entity, so it is not managed: no identity map entry, no dirty checking and changes to it are not saved. That is the point for read paths, and the reason to avoid projecting when you intend to modify:
@Transactional
public void approve(Long id) {
Order order = orders.findById(id).orElseThrow(); // entity: managed, tracked
order.approve(); // dirty checking writes the update
}If findById were shadowed with a projection return type as in the first example, the call would return the projection and this code would not compile; keep a clear separation, with projection methods named for what they return (findSummaryById). A projection is a read model.
Pagination and sorting
Projections work with Pageable and Sort, and a count query is derived from the same conditions:
Page<OrderSummary> findByStatus(String status, Pageable pageable);Page<OrderSummary> page = orders.findByStatus("NEW", PageRequest.of(0, 20, Sort.by("placedAt").descending()));Sorting by a property that the projection does not include still works, since the sort is applied to the entity property in the query. For native queries, pagination requires an explicit countQuery, and sorting is not applied from Sort automatically on all drivers.
Native queries
Interface projections also work with native SQL, with columns aliased to match the getters:
@Query(value = """
select o.reference as reference, count(l.id) as lineCount
from orders o left join order_line l on l.order_id = o.id
group by o.reference
""", nativeQuery = true)
List<OrderCounts> countLines();
public interface OrderCounts {
String getReference();
long getLineCount();
}The alias casing matters on some databases: PostgreSQL folds unquoted aliases to lower case, so lineCount becomes linecount, and Spring Data's matching is case insensitive for tuple aliases in recent versions, but older versions returned null. Quote the alias or use snake case in SQL and map explicitly if a value arrives as null.
Choosing
| Need | Use |
|---|---|
| A few columns, read only, simple | Closed interface projection or a record |
| Serialise straight to JSON, no proxies | Record or class DTO |
| Different views from one method | Dynamic projection |
| A derived label | Default method on a closed projection |
| Joined to-one data | Nested interface projection |
| Joined collections | Two queries, or flat rows grouped in code |
| Update the data | The entity, not a projection |
| Aggregates and reports | JPQL with constructor expressions, or a SQL layer, see Hibernate, JDBC and jOOQ for reports |
Records are the modern default: no proxy, immutable, clear in stack traces and usable in tests without Spring. Interface projections remain the lightest to write and handy when you only read a few properties inside a method.
Verify the effect
A projection that silently falls back to the full entity gains nothing, so check. Log the SQL once while writing the method, and add a test that asserts the query shape with Hibernate statistics or a datasource proxy, as in detecting N plus 1 queries in tests:
@DataJpaTest
class OrderProjectionTest {
@Autowired OrderRepository orders;
@Autowired TestEntityManager em;
@Test
void summariesCarryOnlyTheRequestedFields() {
em.persist(new Order("A-1", "NEW", new BigDecimal("30.00")));
em.flush();
em.clear();
List<OrderSummary> result = orders.findByStatus("NEW");
assertThat(result).singleElement().satisfies(s -> {
assertThat(s.getReference()).isEqualTo("A-1");
assertThat(s.getTotal()).isEqualByComparingTo("30.00");
});
assertThat(em.getEntityManager().getEntityManagerFactory().getPersistenceUnitUtil()
.isLoaded(result.get(0))).isFalse(); // it is not a managed entity
}
}When this does not apply
If the screen really needs the whole entity and its associations, load them with a fetch join or an entity graph. For a handful of rows with narrow tables, the saving is negligible and a projection adds a type to maintain. Hibernate's @Subselect and database views give another way to expose a read model. The reference is the Spring Data JPA documentation on projections, and Hibernate's side of constructor expressions is in the Hibernate user guide on HQL select clauses.


