AI Hints
Home›Spring Boot Tutorial›Derived Query Methods, More Query Keywords and Sorting
Spring Boot · Lesson 55 of 120

Derived Query Methods

Queries from method names.

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

Find all, and find by id, aren't enough. We want books by an author, or under a price. Spring Data can write those queries, just from a method's name.

  • findAll isn't enough
  • By author, under a price
  • Queries from names

How a name becomes a query

The name starts with find by. Then comes a field of the entity, like author. Then, optionally, a keyword, like less than. The parameters fill in the values, in order. And Spring Data builds the query, when the app starts.

  1. findBy
  2. + field: Author
  3. + keyword: LessThan
  4. + parameters
  5. → a query at startup

Three query methods

Find by author finds books with exactly that author. Find by price less than finds books cheaper than max. And find by title returns an Optional, because there's at most one match. We only write these declarations. Spring Data writes the code.

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

    List<Book> findByAuthor(String author);

    List<Book> findByPriceLessThan(double max);

    Optional<Book> findByTitle(String title);
}

Running the queries

Our database starts with eight books. This runner calls each query, and prints the result. Run it. Jane Austen has two books. Two books cost less than eight. Emma is found, wrapped in an Optional. And Ulysses isn't in the shop, so the Optional is empty.

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("By Austen: " + books.findByAuthor("Jane Austen"));
        System.out.println("Under 8: " + books.findByPriceLessThan(8));
        System.out.println("Emma: " + books.findByTitle("Emma"));
        System.out.println("Ulysses: " + books.findByTitle("Ulysses"));
    }
}
Output
By Austen: [Book 7: Emma (6.99), Book 8: Persuasion (7.49)]
Under 8: [Book 7: Emma (6.99), Book 8: Persuasion (7.49)]
Emma: Optional[Book 7: Emma (6.99)]
Ulysses: Optional.empty
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> {

    List<Book> findByAuthor(String author);

    List<Book> findByPriceLessThan(double max);

    Optional<Book> findByTitle(String title);
}
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

Spring Data builds queries from method names: find by, a field, and an optional keyword. Next, more query keywords.

Key takeaways
  • findByAuthor
  • findByPriceLessThan
  • Optional for one result
Next up: More Query Keywords — And, Between, Containing