TExcelTAD
Home › Spring Boot › Query Methods

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

java
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:

java · try it yourself
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:

java
@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 SQL

JPQL 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:

java
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, done
bash · try it yourself
curl -s localhost:8080/api/tasks/stats
[{"priority":"LOW","total":2},{"priority":"MEDIUM","total":5},{"priority":"HIGH","total":1}]
text
Hibernate: select t1_0.priority,count(t1_0.id) from tasks t1_0 group by t1_0.priority

Tip: Rule of thumb: derived queries for one or two simple conditions; @Query beyond 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?

  1. findOpenTasksByText
  2. findByTitleContainingIgnoreCaseAndDoneFalse
  3. searchTitleLike
  4. findByTitleAndDone

What happens if a derived query references a property that does not exist?

  1. The method returns an empty list
  2. Startup fails with a 'No property found' error
  3. A runtime SQL error on first call
  4. The condition is ignored

In a JPQL @Query, what do you reference?

  1. Table and column names
  2. Entity class and field names
  3. JSON property names
  4. Only native SQL