Skip to lesson

Projections and DTO queries

A product list screen shows names and prices, yet loading whole entities sends every column and makes Hibernate keep a copy of each row. On a table with long descriptions and images that gets expensive.

Interface projections and the narrower SELECT they produce

A projection is a query result type that holds only some of an entity's fields, such as an interface with getName() and getPrice(). Spring Data selects just those columns.

A list that shows names and prices needs two columns, not seven. Declare an interface with two getters and read the SQL it sends.

Example 1 · An interface projection: ProductSummary with getName and getPrice

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

ProductSummary.javaJava
// src/main/java/com/shoplite/product/ProductSummary.java (first version)package com.shoplite.product;
import java.math.BigDecimal;
/** A closed interface projection: only the name and the price of a product. */public interface ProductSummary {
    String getName();
    BigDecimal getPrice();}
// ProductRepositoryList<ProductSummary> findSummariesByCategoryId(Integer categoryId);
// ProjectionTour (profile "projection")for (ProductSummary s : products.findSummariesByCategoryId(5)) {    System.out.println("  " + s.getName() + " costs Rs " + s.getPrice());}System.out.println("  class: " + products.findSummariesByCategoryId(5).get(0).getClass().getSimpleName());
Sample output
--- findSummariesByCategoryId(5) (interface projection)
DEBUG org.hibernate.SQL : select p1_0.name,p1_0.price from products p1_0 where p1_0.category_id=?
  Clean Code costs Rs 499.00
  The Pragmatic Programmer costs Rs 650.00
  Atomic Habits costs Rs 399.00
DEBUG org.hibernate.SQL : select p1_0.name,p1_0.price from products p1_0 where p1_0.category_id=?
  class: $Proxy128

What this code does

  • The SELECT lists only name and price: Spring Data read the getters of ProductSummary and asked for nothing else. The same method returning Product would select all seven columns.
  • Each result is a small proxy ($Proxy128, the number varies) that implements the interface and holds the two values. It is not an entity, so Hibernate does not track it for changes.
  • find...By ignores the word between find and By, so findSummariesByCategoryId is just a readable name for "by category id".

Spring Data returns small proxies that implement the interface. Loading entities for a list screen sends every column, makes Hibernate keep a copy of each object to detect changes, and later can trigger lazy loading. On a products table with long descriptions and images, that difference is large.

The getter names must match entity field names (getPrice matches price). A wrong name fails at startup, just like a wrong derived query.

Predict the output

Which columns are selected?

Pick the SELECT list Spring Data sends for each return type.

Round 1 of 2

The return type is the interface ProductSummary.

interface ProductSummary {
String getName();
BigDecimal getPrice();
}
List<ProductSummary> findSummariesByCategoryId(Integer categoryId);

Record projections with a JPQL constructor expression

A constructor expression, select new pkg.Type(a, b), tells JPQL to build one object of your class from each result row. With a Java record the result is immutable and typed.

The product list also needs categoryName from the categories table. Build a record from a join, in one query.

Example 2 · A record projection built by a JPQL constructor expression

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

ProductSummary.javaJava
// src/main/java/com/shoplite/product/ProductSummary.java (the record that replaces the interface)package com.shoplite.product;
import java.math.BigDecimal;
/** One product in a list: exactly the product JSON from the API contract, built by the query. */public record ProductSummary(Integer id, String sku, String name, Integer categoryId, String categoryName,                             BigDecimal price, int stock, boolean isActive) {}
// ProductRepository@Query("""        select new com.shoplite.product.ProductSummary(            p.id, p.sku, p.name, p.categoryId, c.name, p.price, p.stock, p.active)        from Product p        join Category c on c.id = p.categoryId        where p.active = true        order by p.id""")List<ProductSummary> findActiveSummaries();
// ProjectionTourproducts.findActiveSummaries().stream().limit(3).forEach(s -> System.out.println("  " + s));
Sample output
--- findActiveSummaries() (record + constructor expression)
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.sku,p1_0.name,p1_0.category_id,c1_0.name,p1_0.price,p1_0.stock,p1_0.is_active from products p1_0 join categories c1_0 on c1_0.category_id=p1_0.category_id where p1_0.is_active=true order by p1_0.product_id
  ProductSummary[id=1, sku=MOB-RN13, name=Redmi Note 13 5G, categoryId=2, categoryName=Mobiles, price=17999.00, stock=40, isActive=true]
  ProductSummary[id=2, sku=MOB-GM35, name=Samsung Galaxy M35, categoryId=2, categoryName=Mobiles, price=19999.00, stock=25, isActive=true]
  ProductSummary[id=3, sku=MOB-IP15, name=iPhone 15 128GB, categoryId=2, categoryName=Mobiles, price=69900.00, stock=8, isActive=true]

What this code does

  • select new com.shoplite.product.ProductSummary(...) calls the record's constructor once per row, with the values in the listed order. The class name must be fully qualified.
  • join Category c on c.id = p.categoryId joins two entities on a plain id field (Hibernate 6+). One SQL statement now returns every product with its category name, instead of one extra SELECT per product.
  • The record is immutable and not an entity: no proxies, no lazy loading, nothing for Hibernate to track.

Example 3 · A constructor expression with one argument missing

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

Java
// categoryName (c.name) is missing: 7 arguments for an 8-component record@Query("select new com.shoplite.product.ProductSummary(p.id, p.sku, p.name, p.categoryId, p.price, p.stock, p.active) from Product p")List<ProductSummary> findSummariesBroken();
Sample output
ERROR o.s.boot.SpringApplication : Application run failed
...
Caused by: java.lang.IllegalArgumentException: org.hibernate.query.SemanticException: Missing constructor for type 'ProductSummary' [select new com.shoplite.product.ProductSummary(p.id, p.sku, p.name, p.categoryId, p.price, p.stock, p.active) from Product p]
Caused by: org.hibernate.query.SemanticException: Missing constructor for type 'ProductSummary' [select new com.shoplite.product.ProductSummary(p.id, p.sku, p.name, p.categoryId, p.price, p.stock, p.active) from Product p]

What this code does

  • Hibernate looks for a constructor whose parameter count and types match the selected values. None takes 7 values, so startup fails with "Missing constructor for type 'ProductSummary'".
  • The same error appears when the order or a type is wrong, for example p.stock (int) where the record expects a String. Compare the select list with the record components one by one.

A constructor expression shines when the result combines data from several entities: the join runs once and fills categoryName in, which removes the "one extra query per product" problem.

The rules: the class name is fully qualified, the arguments match a constructor in number, order and type, and a wrong list fails at startup with "Missing constructor for type". For simple cases a derived query can also return a record without @Query, matching components to fields by name.

Fix the error

Match the constructor

The record has four components. Pick the line that fixes the query.

Which line gives the record all four values in order?

record ProductSummary(Integer id, String sku, String name, BigDecimal price) { }
@Query("select new com.shoplite.product.ProductSummary(p.id, p.sku, p.price) from Product p")
List<ProductSummary> findSummaries();

Error

Missing constructor for type 'ProductSummary'
ProductSummary is now a record. It replaces the interface from the first section; the rest of the course uses the record.

Dynamic projections with a Class<T> parameter

A dynamic projection is a repository method with a Class<T> parameter, so the caller picks the result type on each call: <T> List<T> findByCategoryId(Integer id, Class<T> type).

Different screens need different shapes of the same query. One method can return entities, records or interface proxies.

Example 4 · Dynamic projections with a Class<T> parameter

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

ProductPrice.javaJava
// src/main/java/com/shoplite/product/ProductPrice.java/** A tiny record projection: the record component names must match Product field names. */public record ProductPrice(String sku, BigDecimal price) {}
// ProductRepositoryList<ProductPrice> findPricesByCategoryId(Integer categoryId);
<T> List<T> findByCategoryId(Integer categoryId, Class<T> type);
// ProjectionTourproducts.findPricesByCategoryId(5).forEach(p -> System.out.println("  " + p));products.findByCategoryId(5, Product.class).forEach(p -> System.out.println("  " + p.getName()));products.findByCategoryId(5, ProductPrice.class).forEach(p -> System.out.println("  " + p));
Sample output
--- findPricesByCategoryId(5) (record, derived query)
DEBUG org.hibernate.SQL : select p1_0.sku,p1_0.price from products p1_0 where p1_0.category_id=?
  ProductPrice[sku=BK-CLEAN, price=499.00]
  ProductPrice[sku=BK-PRAG, price=650.00]
  ProductPrice[sku=BK-ATOMIC, price=399.00]
--- findByCategoryId(5, Product.class)
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.category_id=?
  Clean Code
  The Pragmatic Programmer
  Atomic Habits
--- findByCategoryId(5, ProductPrice.class)
DEBUG org.hibernate.SQL : select p1_0.sku,p1_0.price from products p1_0 where p1_0.category_id=?
  ProductPrice[sku=BK-CLEAN, price=499.00]
  ProductPrice[sku=BK-PRAG, price=650.00]
  ProductPrice[sku=BK-ATOMIC, price=399.00]

What this code does

  • A derived query can return a record directly: Spring Data reads the component names sku and price, matches them to entity fields, and selects only those columns. No @Query needed.
  • With Class<T> type the caller picks the shape for each call: Product.class gives entities (all columns), ProductPrice.class gives records (two columns). One method, three shapes.

One dynamic method avoids writing three nearly identical methods. The service decides what it needs: Product.class when it will change the data, a small record such as ProductPrice.class for a dropdown list.

Use it with care: the method signature no longer tells the reader what comes back, and a type whose names do not match entity fields fails only when it is first used with that type, not at startup.

Closed vs open projections: @Value expressions load the whole entity

An open projection has a getter with @Value("#{target...}"), a SpEL expression computed in Java from the whole entity. A closed projection has only getters that match entity fields.

A label such as "Clean Code (BK-CLEAN)" looks like a cheap projection. Check the SQL it sends.

Example 5 · An open projection loads the whole entity

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

ProductLabel.javaJava
// src/main/java/com/shoplite/product/ProductLabel.javapackage com.shoplite.product;
import org.springframework.beans.factory.annotation.Value;
/** An open projection: getLabel is computed in Java from the whole entity. */public interface ProductLabel {
    @Value("#{target.name + ' (' + target.sku + ')'}")    String getLabel();}
// ProductRepositoryList<ProductLabel> findLabelsByCategoryId(Integer categoryId);
// ProjectionTourfor (ProductLabel label : products.findLabelsByCategoryId(5)) {    System.out.println("  " + label.getLabel());}
Sample output
--- findLabelsByCategoryId(5) (open projection)
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.category_id=?
  Clean Code (BK-CLEAN)
  The Pragmatic Programmer (BK-PRAG)
  Atomic Habits (BK-ATOMIC)

What this code does

  • @Value("#{target...}") is a SpEL expression evaluated in Java on the loaded entity (target). Spring Data cannot know which fields it uses, so it selects every column.
  • The result looks small, but the SQL is as wide as a full entity load. A closed projection with getName() and getSku(), or a record, would select two columns.

Open projections are convenient for small computed fields. The hidden cost is in the log: Spring Data cannot see inside the expression, so it loads the full entity and the SELECT lists every column.

Prefer computing such values in the record itself (a method on the record) or in the service, and keep projections closed.

Returning records from the repository straight to the response

A DTO record is a Java record that carries exactly the fields an API response needs. When a projection record has the contract's fields, the service can return it unchanged and Jackson writes it as JSON.

The list endpoint can return the query's records directly. No entity is loaded and no mapping code is written.

Example 6 · Records from the repository straight to the JSON response

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

Java
// ProductServicepublic List<ProductSummary> listActive() {    return products.findActiveSummaries();   // records from the query, ready for JSON}
// ProductController@GetMappingList<ProductSummary> list() {    return productService.listActive();}
Sample output
$ curl -i http://localhost:8080/api/v1/products
HTTP/1.1 200
Content-Type: application/json
Content-Length: 1941
Date: Fri, 16 Oct 2026 06:21:33 GMT

[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true},{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true},...]

Server log:
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.sku,p1_0.name,p1_0.category_id,c1_0.name,p1_0.price,p1_0.stock,p1_0.is_active from products p1_0 join categories c1_0 on c1_0.category_id=p1_0.category_id where p1_0.is_active=true order by p1_0.product_id

What this code does

  • One SQL statement for the whole list, with the category names joined in. Before, each product needed a second SELECT for its category name.
  • The record's component names are the contract's JSON names (categoryName, isActive), so Jackson writes it with no mapping code. The response is cut after three items here.
  • This lab list has no paging yet. The project lesson wraps it in the contract's page envelope with page and size.

The SQL selects exactly the fields the client sees. This is still layered correctly: the controller calls the service, the service calls the repository, and no entity leaves the service. The record is a DTO that happens to be produced by the query.

When the screen's shape drifts from the table, for example a computed total or a nested list, map in the service instead. Projections are for flat, read-only views.

Next step

Check your understanding

12 quick questions