AI Hints
Home›Spring Boot Tutorial›Counting and Exists, Transactions and Practice: Search Books
Spring Boot · Lesson 63 of 120

Practice: Search Books

Your turn.

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

Let's practise queries. The controller is ready. It needs one repository method, to search titles, with a price limit.

  • Controller is ready
  • One query method
  • Search with a limit

The controller

Search takes some text, q, and a max price, which defaults to a hundred. It calls a long repository method, sorted by price. Long names are fine, when they read clearly.

BookController.javajava
@RestController
public class BookController {
    private final BookRepository books;
    public BookController(BookRepository books) { this.books = books; }

    @GetMapping("/books/search")
    public List<Book> search(@RequestParam String q,
                             @RequestParam(defaultValue = "100") double max) {
        return books.findByTitleContainingIgnoreCaseAndPriceLessThanEqual(
            q, max, Sort.by("price"));
    }
}

The repository method

Your turn. Pause the video, and try this. Write the repository method the controller calls. Titles containing the text, in any case, priced at or below max, with a Sort. Here is one solution. Each part of the name adds one condition. Dune finds both Dune books, cheapest first. And under nine, only Children of Dune remains.

✍️ Exercise: The repository method

Declare findByTitleContainingIgnoreCaseAndPriceLessThanEqual(String text, double max, Sort sort) in BookRepository.

Show hint

Containing + IgnoreCase for the title, LessThanEqual for the price, Sort as the last parameter

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

    List<Book> findByTitleContainingIgnoreCaseAndPriceLessThanEqual(
        String text, double max, Sort sort);
}
Output
$ curl "localhost:8080/books/search?q=dune"
[
  {"id":4,"title":"Children of Dune","author":"Frank Herbert","price":8.49},
  {"id":1,"title":"Dune","author":"Frank Herbert","price":9.99}
]
$ curl "localhost:8080/books/search?q=DUNE&max=9"
[{"id":4,"title":"Children of Dune","author":"Frank Herbert","price":8.49}]

What module seven taught

Derived methods build queries from names, with keywords like And, Between, and Containing. Sort, and Pageable, order and split results. At Query writes JPQL, or native SQL. And at Transactional makes changes all or nothing.

keyvalue
DerivedfindByAuthorAndPrice...
OrderSort, Pageable, Page
Custom@Query JPQL / native
Safety@Transactional

Summary

You can now ask the database almost anything. That's the end of module seven. Next module, relationships between entities.

Key takeaways
  • Query methods
  • Paging and sorting
  • Transactions
Next up: Relationships — entities that know each other