A closed interface projection exposes selected mapped properties through accessor methods instead of returning a complete entity instance.
Spring Data JPA projections: return selected fields without a full entity
The downloadable Spring source kit pins Java 21 and Spring Boot 4.0.8 with its managed dependencies. Run mvn test to check the named fixture.
Ask for the values the caller needs
StockSummary exposes id and available. Its query still filters by available and orders by id, but the caller receives an interface view of the selected values. The test checks three results, the first identifier and its available count, then inspects Hibernate statistics: one prepared statement and zero loaded entities for that operation.
Those statistics are reset after seeding and belong to the pinned fixture. They establish that this query path avoids full entity loading here; they are not a promise that every interface projection, relationship accessor or expression-backed projection has identical SQL behavior. Inspect the actual path you deploy.
A read shape is not an aggregate
The projection is suitable for a bounded stock summary response. It has no business mutation method and is not a replacement for loading an aggregate when an operation requires its invariants. Read Fetch plans before adding nested associations, because a smaller Java interface alone does not establish smaller database work.
Projection getters use the entity property vocabulary. Returning selected values also does not authorize their disclosure: a caller still needs permission to read the stock record. Service authorization belongs outside the choice of query return shape.
Checked source
interface StockSummary {Long getId(); int getAvailable();}
List<StockSummary> findSummaryByAvailableGreaterThanOrderByIdAsc(int minimum);Test the boundary
RepositoryQueryTest.projectionReadsValuesWithoutCreatingAFullEntity checks this contract in the source kit. Excerpts belong to the named classes; use the downloadable files for imports, configuration and assertions.
Costs and boundaries
The fixture selects two values for each of three rows and verifies its Hibernate counters. Returning r projections retains O(r) result objects. Network size and database work can still grow with r. No nested-projection query, production plan or mutation-through-projection behavior is claimed.
Common Mistakes
- Do not assume every projection avoids every entity load.
- Measure nested relationship access separately.
- Choose an aggregate boundary for writes rather than editing a summary view.
Read next
Spring Data JPA repositories: derive a query from mapped properties, Spring JPA fetch plans: measure N+1 queries before changing mappings, Spring method authorization: test the proxied service boundary, Java records: value carriers and defensive copies.
