Query Methods
Spring Data can write queries for you: name a repository method following a small grammar — findBy + property + condition — and the query is derived from the method name. For anything more complex you write JPQL or native SQL in @Query, and for read-only views you can return lightweight projections.
Derived queries
public interface TaskRepository extends JpaRepository<Task, Long> {
List<Task> findByDone(boolean done);
List<Task> findByPriorityAndDoneFalse(Priority priority);
List<Task> findByTitleContainingIgnoreCase(String text);
List<Task> findByDueDateBefore(LocalDate date);
List<Task> findByDueDateBetween(LocalDate from, LocalDate to);
List<Task> findByPriorityIn(Collection<Priority> priorities);
List<Task> findTop3ByDoneFalseOrderByDueDateAsc();
Optional<Task> findFirstByTitleIgnoreCase(String title);
long countByDone(boolean done);
boolean existsByTitleIgnoreCase(String title);
long deleteByDoneTrue(); // needs a transaction
}A misspelled property is caught at startup, not at runtime: findByTitel fails with No property 'titel' found for type 'Task'; Did you mean 'title'.
The grammar
| Keyword | Example | JPQL fragment |
|---|---|---|
And, Or |
findByTitleAndDone |
where title = ?1 and done = ?2 |
Is, Equals (or nothing) |
findByDone |
done = ?1 |
Not |
findByPriorityNot |
priority <> ?1 |
LessThan, GreaterThanEqual |
findByVersionGreaterThan |
version > ?1 |
Before, After, Between |
findByDueDateBefore |
dueDate < ?1 |
IsNull, IsNotNull |
findByDueDateIsNull |
dueDate is null |
Like, Containing, StartingWith |
findByTitleContaining |
title like %?1% |
IgnoreCase |
findByTitleIgnoreCase |
upper(title) = upper(?1) |
True, False |
findByDoneFalse |
done = false |
In |
findByPriorityIn |
priority in ?1 |
OrderBy…Asc/Desc |
…OrderByDueDateDesc |
order by dueDate desc |
Top/First + n |
findTop3By… |
limit 3 |
How a method name becomes a query
Spring Data splits the name at keywords and maps each part to a property and operator. This program implements a small subset of that parser:
import java.util.ArrayList;
import java.util.List;
class Main {
static String toJpql(String method) {
if (!method.startsWith("findBy")) throw new IllegalArgumentException("unsupported: " + method);
String rest = method.substring("findBy".length());
String order = "";
int ob = rest.indexOf("OrderBy");
if (ob >= 0) {
String o = rest.substring(ob + "OrderBy".length());
String dir = o.endsWith("Desc") ? "desc" : "asc";
String prop = o.replaceAll("(Asc|Desc)quot;, "");
order = " order by t." + decap(prop) + " " + dir;
rest = rest.substring(0, ob);
}
List<String> conditions = new ArrayList<>();
int param = 1;
for (String part : rest.split("And")) {
String c;
if (part.endsWith("False")) c = "t." + decap(cut(part, "False")) + " = false";
else if (part.endsWith("True")) c = "t." + decap(cut(part, "True")) + " = true";
else if (part.endsWith("Containing")) c = "t." + decap(cut(part, "Containing")) + " like %?" + param++ + "%";
else if (part.endsWith("Before")) c = "t." + decap(cut(part, "Before")) + " < ?" + param++;
else if (part.endsWith("IsNull")) c = "t." + decap(cut(part, "IsNull")) + " is null";
else c = "t." + decap(part) + " = ?" + param++;
conditions.add(c);
}
return "select t from Task t where " + String.join(" and ", conditions) + order;
}
static String cut(String s, String suffix) { return s.substring(0, s.length() - suffix.length()); }
static String decap(String s) { return Character.toLowerCase(s.charAt(0)) + s.substring(1); }
public static void main(String[] args) {
for (String m : List.of("findByDone", "findByPriorityAndDoneFalse",
"findByTitleContaining", "findByDueDateBeforeAndDoneFalseOrderByDueDateAsc",
"findByDueDateIsNullOrderByTitleDesc")) {
System.out.println(m);
System.out.println(" " + toJpql(m));
}
}
}findByDone
select t from Task t where t.done = ?1
findByPriorityAndDoneFalse
select t from Task t where t.priority = ?1 and t.done = false
findByTitleContaining
select t from Task t where t.title like %?1%
findByDueDateBeforeAndDoneFalseOrderByDueDateAsc
select t from Task t where t.dueDate < ?1 and t.done = false order by t.dueDate asc
findByDueDateIsNullOrderByTitleDesc
select t from Task t where t.dueDate is null order by t.title desc
@Query: write the query yourself
When the name would become unreadable, or you need joins and aggregates, write JPQL:
@Query("""
select t from Task t
where t.done = false and (t.dueDate is null or t.dueDate <= :until)
order by t.priority desc, t.dueDate
""")
List<Task> agenda(@Param("until") LocalDate until);
@Query("select t.priority as priority, count(t) as total from Task t group by t.priority")
List<PriorityCount> countPerPriority();
@Modifying
@Query("update Task t set t.done = true where t.dueDate < :date")
int completeAllBefore(@Param("date") LocalDate date);
@Query(value = "select * from tasks where title ilike '%' || :q || '%'", nativeQuery = true)
List<Task> searchNative(@Param("q") String q); // PostgreSQL-specific SQLJPQL uses entity and field names (Task, dueDate), not table and column names. Named parameters (:until) are bound safely — never concatenate user input into a query string.
Projections
Loading full entities just to show a list wastes memory and columns. A projection selects only what you need. Interface or record projections both work:
public record TaskSummary(Long id, String title, boolean done) {}
public interface PriorityCount {
Priority getPriority();
long getTotal();
}
List<TaskSummary> findByDoneFalse(); // Spring Data selects only id, title, donecurl -s localhost:8080/api/tasks/stats[{"priority":"LOW","total":2},{"priority":"MEDIUM","total":5},{"priority":"HIGH","total":1}]
Hibernate: select t1_0.priority,count(t1_0.id) from tasks t1_0 group by t1_0.priorityTip: Rule of thumb: derived queries for one or two simple conditions;
@Querybeyond that; Specifications or Querydsl when filters are combined dynamically from user input.
Test yourself
Which method name finds open tasks whose title contains a text, ignoring case?
findOpenTasksByTextfindByTitleContainingIgnoreCaseAndDoneFalsesearchTitleLikefindByTitleAndDone
What happens if a derived query references a property that does not exist?
- The method returns an empty list
- Startup fails with a 'No property found' error
- A runtime SQL error on first call
- The condition is ignored
In a JPQL @Query, what do you reference?
- Table and column names
- Entity class and field names
- JSON property names
- Only native SQL