@Query with JPQL
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A derived name with four conditions is unreadable, and a report needs a join or a sum. ShopLite wants queries a teammate can read in a code review and that fail on a laptop, not in production.
JPQL uses entity and field names, not table and column names
JPQL (Jakarta Persistence Query Language) is SQL-like text written against your entities and their fields instead of tables and columns. Put it in @Query and Hibernate translates it into MySQL SQL.
Here is the long derived name from the last lesson beside a JPQL version. Product and p.active are Java names; Hibernate writes the table and column names.
Example 1 · The same query as a derived method and as JPQL
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// src/main/java/com/shoplite/product/ProductRepository.java (two methods)List<Product> findByCategoryIdAndActiveTrueAndStockGreaterThanAndPriceLessThanEqualOrderByPriceAsc( Integer categoryId, int stock, BigDecimal maxPrice);
@Query(""" select p from Product p where p.categoryId = :categoryId and p.active = true and p.stock > 0 and p.price <= :maxPrice order by p.price""")List<Product> findBuyable(@Param("categoryId") Integer categoryId, @Param("maxPrice") BigDecimal maxPrice);
// src/main/java/com/shoplite/lab/JpqlTour.java (profile "jpql")print(products.findByCategoryIdAndActiveTrueAndStockGreaterThanAndPriceLessThanEqualOrderByPriceAsc( 4, 0, new BigDecimal("2500")));print(products.findBuyable(4, new BigDecimal("2500")));--- long derived name vs findBuyable (Accessories up to 2500) 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=? and p1_0.is_active=true and p1_0.stock>? and p1_0.price<=? order by p1_0.price ACC-AD141 1299.00 stock 120 ACC-PB20K 2199.00 stock 60 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=? and p1_0.is_active=true and p1_0.stock>0 and p1_0.price<=? order by p1_0.price ACC-AD141 1299.00 stock 120 ACC-PB20K 2199.00 stock 60
What this code does
- The JPQL says
Product,p.categoryIdandp.active; Hibernate wroteproducts,category_idandis_activefrom the entity mapping. - Both methods send almost the same SQL. The only difference: the literal
0in the JPQL stays a literal, while the derived method binds it as a parameter. select preturns wholeProductentities, so every mapped column is selected.
@Query("select p from Product p where p.active = true") declares a JPQL query: Product is the entity class, p an alias and p.active the Java field. Why a second query language? JPQL is checked against your mapping: rename a field and the query fails at startup, not in production. It also works on any database Hibernate supports, and it can return entities, single values or DTOs.
JPQL looks like SQL on purpose: select, from, where, join, group by, order by, count, sum, lower and between all exist. What it lacks are database-only features such as MySQL's REGEXP or window functions; the next lesson uses native SQL for those.
""", Java 15+) keep long queries readable. Spring Data passes the text to Hibernate unchanged, line breaks included.Named parameters (:name with @Param) and positional ?1
A named parameter is a placeholder such as :threshold that Spring Data fills from the method argument whose @Param has the same name. The value is bound, never glued into the SQL text.
A price filter and a SKU list need user values without gluing text into the query. Compare positional ?1, a named list and the SQL they send.
Example 2 · Positional ?1 ?2 and a named list parameter
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// ProductRepository@Query("select p from Product p where p.price between ?1 and ?2 order by p.price")List<Product> findInPriceRange(BigDecimal min, BigDecimal max);
@Query("select p from Product p where p.sku in :skus order by p.sku")List<Product> findAllBySkus(@Param("skus") Collection<String> skus);
// JpqlTourprint(products.findInPriceRange(new BigDecimal("1000"), new BigDecimal("2500")));print(products.findAllBySkus(List.of("BK-CLEAN", "MOB-RN13", "XX-NONE")));--- findInPriceRange(1000, 2500) (positional ?1 ?2) 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.price between ? and ? order by p1_0.price ACC-AD141 1299.00 stock 120 HK-COOK3L 1899.00 stock 15 ACC-PB20K 2199.00 stock 60 FSH-SHOE 2499.00 stock 18 --- findAllBySkus([BK-CLEAN, MOB-RN13, XX-NONE]) 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.sku in (?,?,?) order by p1_0.sku BK-CLEAN 499.00 stock 30 MOB-RN13 17999.00 stock 40
What this code does
?1is the first method argument and?2the second. Swap the arguments by mistake and you silently get an empty list, which is why named parameters are preferred.- A collection bound to
in :skusbecomes one?per element. The SKU that does not exist simply matches nothing; there is no error.
@Param("threshold") names the parameter explicitly. Spring Boot's Maven parent compiles with -parameters, so the annotation can be left out, but writing it keeps the query correct even if the build changes. A positional parameter ?1, ?2 uses the argument's position instead. It is shorter, but swapping two arguments of the same type gives wrong results with no error, so prefer names.
Either way the value is sent separately from the SQL text, which is what makes JPQL safe from SQL injection. A collection argument works with in :skus.
:limit with @Param("threshold")) is not caught at startup. It fails on the first call with "No argument for named parameter ':limit'".LIKE with lower() and concat(), IN lists, and aggregates
coalesce returns the first value that is not null, so coalesce(sum(x), 0) gives 0 instead of null when there are no rows to add up.
A stock report must not crash for an empty category. Search by name, count, sum, then look at what an empty sum returns.
Example 3 · LIKE with lower() and concat(), count and sum
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// ProductRepository@Query("select p from Product p where lower(p.name) like lower(concat('%', :text, '%')) order by p.id")List<Product> searchByName(@Param("text") String text);
@Query("select count(p) from Product p where p.categoryId = :categoryId")long countInCategory(@Param("categoryId") Integer categoryId);
@Query("select sum(p.price * p.stock) from Product p where p.categoryId = :categoryId")BigDecimal stockValue(@Param("categoryId") Integer categoryId);
@Query("select coalesce(sum(p.price * p.stock), 0) from Product p where p.categoryId = :categoryId")BigDecimal stockValueOrZero(@Param("categoryId") Integer categoryId);
// JpqlTourprint(products.searchByName("es"));long count = products.countInCategory(4);System.out.println(count);BigDecimal books = products.stockValue(5);BigDecimal none = products.stockValue(99);System.out.println(books + " and " + none);System.out.println(products.stockValueOrZero(99));--- searchByName("es")
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 lower(p1_0.name) like lower(concat('%',?,'%')) escape '' order by p1_0.product_id
ACC-AD141 1299.00 stock 120
FSH-SHOE 2499.00 stock 18
HK-COOK3L 1899.00 stock 15
--- countInCategory(4)
DEBUG org.hibernate.SQL : select count(p1_0.product_id) from products p1_0 where p1_0.category_id=?
4
--- stockValue(5) and stockValue(99)
DEBUG org.hibernate.SQL : select sum((p1_0.price*p1_0.stock)) from products p1_0 where p1_0.category_id=?
DEBUG org.hibernate.SQL : select sum((p1_0.price*p1_0.stock)) from products p1_0 where p1_0.category_id=?
49220.00 and null
--- stockValueOrZero(99)
DEBUG org.hibernate.SQL : select coalesce(sum((p1_0.price*p1_0.stock)),0) from products p1_0 where p1_0.category_id=?
0.00What this code does
- "es" matched boAt Airdopes, Running Shoes and Prestige:
lower()on both sides makes the search ignore case on any database. count(p)returnslong.sumofBigDecimalvalues returnsBigDecimal: the books are worth 499×30 + 650×22 + 399×50 = 49220.00 rupees in stock.- Category 99 has no products, and SQL's
sumover no rows isnull, not 0. Unboxing that into alongor calling.add()on it throwsNullPointerException;coalesce(..., 0)returns 0 instead.
Search text is written as lower(p.name) like lower(concat('%', :text, '%')): concat builds the pattern around the bound value and lower on both sides ignores case. Unlike Containing in a derived query, this does not escape % or _ typed by the user; a search for "50%" would treat % as a wildcard.
Aggregates return single values: count(p) gives a long, sum, min and max of a BigDecimal field give a BigDecimal, and avg gives a Double. Declare the return type to match. sum over zero rows is null in SQL, so wrap it in coalesce(sum(...), 0), or the first empty category breaks your report with a NullPointerException.
Predict the output
What does the sum return?
Category 99 has no products. Pick what each method returns.
Round 1 of 2
The query is select sum(p.price * p.stock) for category 99.
JPQL is checked at startup: "Could not resolve attribute" and unknown entities
Query validation means Hibernate parses every @Query JPQL string against the entity mapping when the repository is created. A wrong field or entity name stops the application with "Query validation failed".
A column name inside JPQL should fail on your laptop, not in production. Here are the two classic mistakes and what the startup log says.
Example 4 · JPQL mistakes stop the application at startup
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// Mistake 1: a column name instead of the field name@Query("select p from Product p where p.is_active = true and p.stock < :threshold")List<Product> findLowStockBroken(@Param("threshold") int threshold);
// Mistake 2: the table name instead of the entity name@Query("select p from products p where p.stock < :threshold")List<Product> findLowStockBroken(@Param("threshold") int threshold);Mistake 1: Caused by: org.springframework.data.repository.query.QueryCreationException: Cannot create query for method [ProductRepository.findLowStockBroken(int)]; Query validation failed for 'select p from Product p where p.is_active = true and p.stock < :threshold' Caused by: java.lang.IllegalArgumentException: org.hibernate.query.sqm.UnknownPathException: Could not resolve attribute 'is_active' of 'com.shoplite.product.Product' [select p from Product p where p.is_active = true and p.stock < :threshold] Caused by: org.hibernate.query.sqm.PathElementException: Could not resolve attribute 'is_active' of 'com.shoplite.product.Product' Mistake 2: Caused by: org.springframework.data.repository.query.QueryCreationException: Cannot create query for method [ProductRepository.findLowStockBroken(int)]; Query validation failed for 'select p from products p where p.stock < :threshold' Caused by: java.lang.IllegalArgumentException: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'products' Caused by: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'products'
What this code does
- Each mistake was built and started separately; both apps stopped before Tomcat opened a port. The useful lines are the last
Caused byof each. - "Could not resolve attribute 'is_active'" means "Product has no field called is_active" (the field is
active). "Could not resolve root entity 'products'" means "no entity called products" (it isProduct).
The last Caused by line tells you exactly what is wrong. "Could not resolve attribute 'is_active' of 'com.shoplite.product.Product'" means you used a column name where JPQL wants the field active. "Could not resolve root entity 'products'" means you wrote the table name; the entity is Product.
For interviews: JPQL errors fail fast, native SQL errors fail late. This startup check is one of the biggest reasons to prefer JPQL over native SQL.
Fix the error
Fix the JPQL
The app stops at startup. Pick the line that fixes it.
Round 1 of 2
Which line fixes the attribute error?
Error
Could not resolve attribute 'is_active' of 'com.shoplite.product.Product'
A ShopLite low-stock query
The shop owner checks stock every morning before the college fest rush. One query lists active products under a threshold, most urgent first.
Example 5 · A ShopLite low-stock query, from repository to service
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// src/main/java/com/shoplite/product/ProductRepository.java/** Active products running out: fewest units first, ties by id. */@Query(""" select p from Product p where p.active = true and p.stock < :threshold order by p.stock, p.id""")List<Product> findLowStock(@Param("threshold") int threshold);
// src/main/java/com/shoplite/product/ProductService.java/** Active products with fewer than threshold units, for the stock report. */public List<ProductResponse> lowStock(int threshold) { return products.findLowStock(threshold).stream() .map(p -> ProductResponse.from(p, categoryName(p.getCategoryId()))) .toList();}
// JpqlTourprint(products.findLowStock(10));--- findLowStock(10) 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.is_active=true and p1_0.stock<? order by p1_0.stock,p1_0.product_id ACC-M331 849.00 stock 0 LAP-HPV15 64990.00 stock 5 MOB-IP15 69900.00 stock 8
What this code does
- ACC-USBC1 also has stock 0 but is inactive, so it is not on the list: nobody needs to reorder a product the shop no longer sells.
order by p.stock, p.idputs the most urgent product first and breaks ties by id, so the report is always in the same order.- The service turns entities into
ProductResponserecords before anything leaves it, as with every ShopLite read.
The query holds the JPQL checklist in one place: entity and field names, a named parameter, a filter that skips inactive products, and an ORDER BY with a unique tiebreaker (p.id) so the order never changes between runs.
The service wraps it and returns DTOs, so the repository can change (more columns, a projection later) without touching any controller.
Next step
Check your understanding
12 quick questions