Derived query methods from method names
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite needs dozens of small lookups: a product by SKU, a customer by e-mail, "is this e-mail already taken?". A SQL string and row mapping for each one is slow to write and easy to get wrong.
findBySku, findByEmailIgnoreCase, existsByEmail, countByActiveTrue
A derived query is a query built from a repository method's name. Spring Data reads words such as findBySku or existsByEmail, works out the WHERE clause and writes the SQL for you.
findBySku(String sku) means "select products where sku = ?". Four everyday lookups follow, with the SQL each one sends.
Example 1 · Four everyday lookups and the SQL Spring Data writes
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// src/main/java/com/shoplite/product/ProductRepository.java (methods for this example)Optional<Product> findBySku(String sku);
long countByActiveTrue();
// src/main/java/com/shoplite/customer/CustomerRepository.javapublic interface CustomerRepository extends JpaRepository<Customer, Integer> {
Optional<Customer> findByEmailIgnoreCase(String email);
boolean existsByEmail(String email);}
// src/main/java/com/shoplite/lab/DerivedTour.java (part "basic")private void basics() { System.out.println("--- findBySku(\"MOB-IP15\")"); System.out.println(products.findBySku("MOB-IP15").map(Product::getName).orElse("none"));
System.out.println("--- findByEmailIgnoreCase(\"Asha.Rao@Example.com\")"); System.out.println(customers.findByEmailIgnoreCase("Asha.Rao@Example.com") .map(Customer::getFullName).orElse("none"));
System.out.println("--- existsByEmail(\"ravi.kumar@example.com\")"); System.out.println(customers.existsByEmail("ravi.kumar@example.com"));
System.out.println("--- countByActiveTrue()"); System.out.println(products.countByActiveTrue());}$ mvn spring-boot:run -Dspring-boot.run.profiles=derived -Dspring-boot.run.arguments=basic
...
--- findBySku("MOB-IP15")
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=?
iPhone 15 128GB
--- findByEmailIgnoreCase("Asha.Rao@Example.com")
DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where upper(c1_0.email)=upper(?)
Asha Rao
--- existsByEmail("ravi.kumar@example.com")
DEBUG org.hibernate.SQL : select c1_0.customer_id from customers c1_0 where c1_0.email=? limit ?
true
--- countByActiveTrue()
DEBUG org.hibernate.SQL : select count(p1_0.product_id) from products p1_0 where p1_0.is_active=true
14What this code does
findBySkubecomeswhere sku=?; the?is a bound parameter, so the value never becomes part of the SQL text.IgnoreCasewraps both sides inupper(...).existsBy...selects just the id withlimit ?(Spring Data binds 1): it stops at the first match instead of counting every row.countByActiveTrueneeds no parameter: the keywordTrueputsis_active=truestraight into the SQL. 14 of the 15 products are active.
A name starts with a subject (find...By, exists...By, count...By, delete...By) and continues with conditions on entity fields; the parameters fill the conditions in order. Spring Data checks every name against the entity when the app starts, so each lookup is one line instead of a SQL string plus row mapping.
What can go wrong: findByEmailIgnoreCase wraps the column in upper(), so MySQL cannot use the unique index on email and scans the table. ShopLite's email column uses the utf8mb4_0900_ai_ci collation, which already compares without case, so plain existsByEmail matches Asha.Rao@Example.com too and keeps the index.
Optional<T>, many → List<T>, exists → boolean, count → long.Keywords: And, Or, Between, LessThan, GreaterThanEqual, Containing, StartingWith, In, IsNull, OrderBy
A keyword is a word between field names that turns into an SQL operator, such as And, Between, Containing, In, IsNull or OrderBy.
Shop staff filter by price, stock, name and category. Each condition is one keyword in the method name; eight of them follow with their SQL.
Example 2 · Keywords: And, Or, Between, LessThan, Containing, StartingWith, In, IsNull, OrderBy
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// src/main/java/com/shoplite/product/ProductRepository.java (methods for this example)List<Product> findByCategoryIdAndActiveTrue(Integer categoryId);
List<Product> findByStockOrActiveFalse(int stock);
List<Product> findByPriceBetween(BigDecimal min, BigDecimal max);
List<Product> findByStockLessThan(int stock);
List<Product> findByPriceGreaterThanEqualOrderByPriceDesc(BigDecimal price);
List<Product> findByNameContainingIgnoreCase(String text);
List<Product> findBySkuStartingWith(String prefix);
List<Product> findByCategoryIdIn(Collection<Integer> categoryIds);
// CustomerRepositoryList<Customer> findByPhoneIsNull();
// DerivedTour (part "keywords"): each call is printed as " SKU price stock N"print(products.findByCategoryIdAndActiveTrue(4));print(products.findByStockOrActiveFalse(0));print(products.findByPriceBetween(new BigDecimal("500"), new BigDecimal("1000")));print(products.findByStockLessThan(10));print(products.findByPriceGreaterThanEqualOrderByPriceDesc(new BigDecimal("40000")));print(products.findByNameContainingIgnoreCase("PRO"));print(products.findBySkuStartingWith("BK-"));print(products.findByCategoryIdIn(List.of(5, 6)));customers.findByPhoneIsNull().forEach(c -> System.out.println(" " + c.getFullName()));--- findByCategoryIdAndActiveTrue(4)
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
ACC-AD141 1299.00 stock 120
ACC-PB20K 2199.00 stock 60
ACC-M331 849.00 stock 0
--- findByStockOrActiveFalse(0)
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.stock=? or p1_0.is_active=false
ACC-M331 849.00 stock 0
ACC-USBC1 199.00 stock 0
--- findByPriceBetween(500, 1000)
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 ?
ACC-M331 849.00 stock 0
BK-PRAG 650.00 stock 22
FSH-KURTA 899.00 stock 35
--- findByStockLessThan(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.stock<?
MOB-IP15 69900.00 stock 8
LAP-HPV15 64990.00 stock 5
ACC-M331 849.00 stock 0
ACC-USBC1 199.00 stock 0
--- findByPriceGreaterThanEqualOrderByPriceDesc(40000)
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>=? order by p1_0.price desc
MOB-IP15 69900.00 stock 8
LAP-HPV15 64990.00 stock 5
LAP-IPS3 42990.00 stock 12
--- findByNameContainingIgnoreCase("PRO")
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 upper(p1_0.name) like upper(?) escape '\\'
BK-PRAG 650.00 stock 22
--- findBySkuStartingWith("BK-")
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 like ? escape '\\'
BK-ATOMIC 399.00 stock 50
BK-CLEAN 499.00 stock 30
BK-PRAG 650.00 stock 22
--- findByCategoryIdIn([5, 6])
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 in (?,?)
BK-CLEAN 499.00 stock 30
BK-PRAG 650.00 stock 22
BK-ATOMIC 399.00 stock 50
FSH-KURTA 899.00 stock 35
FSH-SHOE 2499.00 stock 18
--- findByPhoneIsNull()
DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.phone is null
Meena Iyer
Arjun MehtaWhat this code does
- Each keyword maps to one piece of SQL:
Between→between ? and ?,LessThan→<,GreaterThanEqual→>=,In→in (?,?),IsNull→is null,OrderBy...Desc→order by ... desc. ContainingandStartingWithbecomelike; Spring Data adds the%around your value and escapes any%or_the user typed, so "PRO" cannot turn into a pattern.- Only
OrderByfixes the order.StartingWith("BK-")came back sorted by SKU only because MySQL happened to read the SKU index; never rely on that.
True and False need no parameter (ActiveTrue). IgnoreCase works on one field (NameContainingIgnoreCase). OrderBy comes last and names fields with Asc or Desc. Without it, MySQL returns rows in whatever order is cheapest, which can change when an index is added, so any list a user sees needs an explicit order.
Details worth remembering:
Containing,StartingWith,EndingWithbecomelikewith%added and user wildcards escapedIntakes aCollection; an empty collection simply matches nothingAndbinds tighter thanOr:findByAOrBAndCmeans A or (B and C)
Predict the output
Read the SQL from the name
Pick the WHERE part Spring Data writes for each method.
Round 1 of 2
Which products cost between 500 and 1000?
findFirst, findTop and Limit; returning Optional, List or Stream
Limit is a parameter type that caps the number of rows, such as Limit.of(5). findFirst and findTopN in a method name cap the rows with a fixed size instead.
A dashboard shows the most expensive product and the top three. Capping rows lets MySQL stop early instead of sending every row.
Example 3 · findFirst, findTop3, a Limit parameter and a Stream
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// src/main/java/com/shoplite/product/ProductRepository.java (methods for this example)Optional<Product> findFirstByOrderByPriceDesc();
List<Product> findTop3ByActiveTrueOrderByPriceDesc();
List<Product> findByCategoryIdOrderByPriceAsc(Integer categoryId, Limit limit);
Stream<Product> streamByCategoryId(Integer categoryId);
// DerivedTour (part "limits"); run() is @Transactional(readOnly = true)System.out.println(products.findFirstByOrderByPriceDesc().map(Product::getName).orElse("none"));print(products.findTop3ByActiveTrueOrderByPriceDesc());print(products.findByCategoryIdOrderByPriceAsc(4, Limit.of(2)));try (Stream<Product> stream = products.streamByCategoryId(3)) { // close it: it holds a JDBC cursor stream.map(p -> " " + p.getName()).forEach(System.out::println);}--- findFirstByOrderByPriceDesc() 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 order by p1_0.price desc limit ? iPhone 15 128GB --- findTop3ByActiveTrueOrderByPriceDesc() 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 order by p1_0.price desc limit ? MOB-IP15 69900.00 stock 8 LAP-HPV15 64990.00 stock 5 LAP-IPS3 42990.00 stock 12 --- findByCategoryIdOrderByPriceAsc(4, Limit.of(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.category_id=? order by p1_0.price limit ? ACC-USBC1 199.00 stock 0 ACC-M331 849.00 stock 0 --- streamByCategoryId(3) 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=? Lenovo IdeaPad Slim 3 HP Victus 15 Gaming
What this code does
FirstandTop3becomelimit ?in MySQL. With one result the return type can beOptional<Product>; with several,List<Product>.Limit.of(2)(Spring Data 3.2+) lets the caller choose the size at runtime.Limit.unlimited()removes the limit.- A
Streamreads rows one by one from an open JDBC result set, so it must run inside a transaction and be closed with try-with-resources.
Example 4 · A Stream without a transaction
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// a runner method with NO @Transactionaltry (Stream<Product> s = products.streamByCategoryId(3)) { s.forEach(System.out::println);}ERROR o.s.boot.SpringApplication : Application run failed org.springframework.dao.InvalidDataAccessApiUsageException: You're trying to execute a streaming query method without a surrounding transaction that keeps the connection open so that the Stream can actually be consumed; Make sure the code consuming the stream uses @Transactional or any other way of declaring a (read-only) transaction
What this code does
- Spring Data refuses to start a stream without a transaction, because the connection would go back to the pool before you read the rows.
- Fix: call it from a
@Transactional(readOnly = true)service method, or return aListwhen the result is small.
findFirstByOrderByPriceDesc() is the most expensive product and findTop3By... the top three; Spring Data adds limit ? to the SQL. When the caller should choose the size, add a Limit parameter (Spring Data 3.2 and later). A Pageable parameter does the same with page numbers; the Pagination module covers it.
A Stream<T> return type reads rows lazily over an open connection. Use it for long exports, always inside a transaction, and always in try-with-resources so the cursor is closed.
Typos fail at startup: "No property 'title' found for type 'Product'"
PropertyReferenceException is the startup error Spring Data throws while it builds the repository proxy, when a derived method name refers to a field the entity does not have.
Writing title when the field is name should fail loudly. Here is what the log shows when the app refuses to start.
Example 5 · A typo in a method name stops the application at startup
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// ProductRepository: Product has no field called "title" (it is "name")List<Product> findByTitle(String title);WARN o.s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: ... ERROR o.s.boot.SpringApplication : Application run failed ... Caused by: org.springframework.data.repository.query.QueryCreationException: Cannot create query for method [ProductRepository.findByTitle(java.lang.String)]; No property 'title' found for type 'Product' ... 36 common frames omitted Caused by: org.springframework.data.core.PropertyReferenceException: No property 'title' found for type 'Product' ... 50 common frames omitted
What this code does
- Spring Data parses every method name when it builds the repository, so the app does not even start. That is good: the bug is found on your laptop, not by a customer.
- Read the last
Caused byline: it names the method and the missing property. Property names are Java field names (name,categoryId,active), never column names.
Read the message from the last Caused by. "No property 'title' found for type 'Product'" means the entity has no title field. A misspelt keyword gives a stranger message: findByStockLessThen reports "No property 'lessThen' found for type 'int'; Traversed path: Product.stock", because Spring Data read Stock as a field and then looked for a field lessThen inside an int.
The fix is always to match the entity's Java field names and the exact keyword spelling. The column names in MySQL do not matter here.
Fix the error
Fix the method name
The app will not start. Pick the line that fixes it.
Round 1 of 2
Which line stops the keyword error?
Error
No property 'lessThen' found for type 'int'; Traversed path: Product.stock
When a method name gets too long: switch to @Query
@Query is an annotation that puts your own query on a repository method, so the method can have a short business name instead of a long derived one.
A name with four conditions and an order is correct but unreadable. Compare it with the same SQL under a business name.
// Works, but hard to read and to changeList<Product> findByCategoryIdAndActiveTrueAndStockGreaterThanAndPriceLessThanEqualOrderByPriceAsc( Integer categoryId, int stock, BigDecimal maxPrice);
// Same SQL, with a name that says what it is for@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);The readability limit comes quickly: changing one condition renames the method everywhere. As a rule of thumb, two or three conditions are fine. Beyond that, or when you need a join, a function such as lower(), an aggregate or a computed value, write the query yourself with @Query. The next lesson covers JPQL.
Next step
Check your understanding
12 quick questions