Custom Queries with @Query
A custom query is a query you write yourself on a repository method. The @Query annotation holds the query text.
A query written by hand
@Query holds the query text above the method.
@Query("SELECT t FROM Task t WHERE t.done = true")
List<Task> findFinished();A named value in the query
A colon marks a named slot. @Param links a method value to the slot.
@Query("SELECT t FROM Task t WHERE t.title = :title")
List<Task> findWithTitle(@Param("title") String title);Example
package com.example.demo;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
private final TaskRepository repository;
public TaskController(TaskRepository repository) {
this.repository = repository;
}
@GetMapping("/tasks/finished")
public List<TaskView> finishedTasks() {
return repository.findFinished().stream()
.map(task -> new TaskView(task.getTitle(), task.isDone()))
.toList();
}
public record TaskView(String title, boolean done) {
}
}Key points
- @Query sits above a repository method.
- The query uses JPQL.
- JPQL names the entity, not the table.
- SELECT t FROM Task t reads every task.
- A WHERE clause filters the rows.
- A named slot in the query starts with a colon.
- @Param links a method value to a named slot.
In this example, the repository carries the custom query. The @Query annotation holds JPQL that reads finished tasks. JPQL names the entity Task, not a table. The controller calls findFinished and maps each task to a TaskView. The exchange shows one finished task, Ship Spring Boot.
Note
A JPQL mistake fails when the app starts, not at the first call.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does JPQL name in SELECT t FROM Task t?