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

Sorting

Put results in order.

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

Results from a database come back in no particular order, unless you ask for one. There are two ways to ask.

  • No order by default
  • Ask for one
  • Two ways

Two ways to sort

Order by, in the method name, fixes the order, like order by price ascending. Or a Sort parameter lets the caller choose. Sort dot by title sorts by title. And dot descending reverses it.

keyvalue
In the name...OrderByPriceAsc
As a parameterSort sort
Sort.by("title")A to Z
.descending()reversed

Sorting in the repository

The first method always sorts by price, cheapest first. The second takes a Sort, chosen by the caller.

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

    List<Book> findByAuthorOrderByPriceAsc(String author);

    List<Book> findByPriceLessThan(double max, Sort sort);
}

Sorted results

First, Tolkien's books by price. Then, find all, with a Sort by title, which every repository supports. Then, books under nine, most expensive first. Run it. The Hobbit is cheaper, so it comes first. The titles are in alphabetical order. And the cheap books go from eight ninety nine, down.

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(books.findByAuthorOrderByPriceAsc("J.R.R. Tolkien"));
        books.findAll(Sort.by("title")).forEach(b -> System.out.println(b.getTitle()));
        var cheap = books.findByPriceLessThan(9, Sort.by("price").descending());
        System.out.println(cheap);
    }
}
Output
[Book 2: The Hobbit (8.99), Book 6: The Fellowship of the Ring (11.99)]
Children of Dune
Circe
Dune
Emma
Persuasion
Song of Achilles
The Fellowship of the Ring
The Hobbit
[Book 2: The Hobbit (8.99), Book 4: Children of Dune (8.49), Book 8: Persuasion (7.49),
Book 7: Emma (6.99)]
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> findByAuthorOrderByPriceAsc(String author);

    List<Book> findByPriceLessThan(double max, Sort sort);
}
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

Sort with order by in the method name, or pass a Sort object, like Sort dot by title, descending. Next, paging.

Key takeaways
  • OrderByPriceAsc
  • Sort.by("title")
  • .descending()
Next up: Paging — one page at a time