AI Hints
Home›Spring Boot Tutorial›Paging, @Query with JPQL and Native Queries
Spring Boot · Lesson 59 of 120

@Query with JPQL

Write your own query.

⏱ 2 min read▶ Video at 1:19:47🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

When a method name gets too long, or the query is too clever for a name, we can write the query ourselves.

  • Names get too long
  • Clever queries
  • Write it yourself

JPQL

At Query holds a query in JPQL, the Java Persistence Query Language. It looks like SQL, but it talks about entities, and fields, not tables, and columns. Colon names, like colon min, are parameters. At Param connects each one to a method parameter.

keyvalue
JPQLSQL-like, for entities
FROM Book bthe entity, not the table
:mina named parameter
@Param("min")fills it in

Three JPQL queries

The first finds books in a price range, sorted by price. The second selects only titles, so it returns strings. And the third works out the average price, with AVG.

BookRepository.javajava
public interface BookRepository extends JpaRepository<Book, Long> {

    @Query("SELECT b FROM Book b WHERE b.price BETWEEN :min AND :max ORDER BY b.price")
    List<Book> inPriceRange(@Param("min") double min, @Param("max") double max);

    @Query("SELECT b.title FROM Book b WHERE b.author = :author")
    List<String> titlesBy(@Param("author") String author);

    @Query("SELECT AVG(b.price) FROM Book b")
    double averagePrice();
}

Running them

We call all three queries. Run it. Three books cost between nine and eleven, cheapest first. Tolkien wrote two of our books. And the average price is nine thirty.

QueryDemo.javajava
@Component
public class QueryDemo implements CommandLineRunner {

    private final BookRepository books;

    public QueryDemo(BookRepository books) { this.books = books; }

    @Override
    public void run(String... args) {
        System.out.println("9 to 11: " + books.inPriceRange(9, 11));
        System.out.println("Tolkien: " + books.titlesBy("J.R.R. Tolkien"));
        System.out.printf("Average price: %.2f%n", books.averagePrice());
    }
}
Output
9 to 11: [Book 5: Song of Achilles (9.49), Book 1: Dune (9.99), Book 3: Circe (10.99)]
Tolkien: [The Hobbit, The Fellowship of the Ring]
Average price: 9.30
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private double price;

    protected Book() {}

    public Book(String title, String author, double price) {
        this.title = title; this.author = author; this.price = price;
    }

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }

    @Override
    public String toString() { return "Book " + id + ": " + title + " (" + price + ")"; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {

    @Query("SELECT b FROM Book b WHERE b.price BETWEEN :min AND :max ORDER BY b.price")
    List<Book> inPriceRange(@Param("min") double min, @Param("max") double max);

    @Query("SELECT b.title FROM Book b WHERE b.author = :author")
    List<String> titlesBy(@Param("author") String author);

    @Query("SELECT AVG(b.price) FROM Book b")
    double averagePrice();
}
Also uses data.sql
INSERT INTO book (title, author, price) VALUES
  ('Dune', 'Frank Herbert', 9.99),
  ('The Hobbit', 'J.R.R. Tolkien', 8.99),
  ('Circe', 'Madeline Miller', 10.99),
  ('Children of Dune', 'Frank Herbert', 8.49),
  ('Song of Achilles', 'Madeline Miller', 9.49),
  ('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
  ('Emma', 'Jane Austen', 6.99),
  ('Persuasion', 'Jane Austen', 7.49);
Also uses application.properties
spring.jpa.defer-datasource-initialization=true

Summary

At Query lets you write JPQL, which uses entity and field names, with colon parameters filled by at Param. Next, native queries.

Key takeaways
  • @Query("SELECT b FROM Book b ...")
  • Named parameters
  • :min + @Param
Next up: Native Queries — plain SQL